在HTML页面中用Javascript调用Wcf服务 [英] Call Wcf service with Javascript in Html page

查看:100
本文介绍了在HTML页面中用Javascript调用Wcf服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VSStudio2012中有一个WCF项目,我想从JavaScript函数调用一个方法。



JavaScript文件:

  var url ='http:// localhost:52768 / Service1.svc /'

function test(){

无功响应;

$ .ajax({
type:'Post',
url:url +'GetTEST',
contentType:'application / json; charset = utf- 8',
dataType:'json',
成功:函数(msg){
alert(msg);
},

错误:函数(e){
alert(Error:+ e.statusText);
}
});

}

HTML档案: p>

 <!DOCTYPE html> 
< html xmlns =http://www.w3.org/1999/xhtml>
< head>
< script Language =JavaScriptsrc =Scripts / JavaScript1.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery-1.10.2.min.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery-1.9.1.intellisense.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery-1.9.1.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery-1.9.1.min.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.unobtrusive-ajax.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.unobtrusive-ajax.min.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.validate.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.validate.min.js>< / script>
< title> TESTE< / title>
< / head>
< body>
< input id =Button1type =buttonvalue =buttononclick =test()/>
< / body>

< / html>

在我的IService1.cs中

  [OperationContract] 
[WebInvoke(Method =GET,ResponseFormat = WebMessageFormat.Json)]
string GetTEST();

这是提醒显示



< img src =https://i.stack.imgur.com/jefQF.pngalt =在这里输入图片描述>



和错误:

p>



localhost:52768 / Service1.svc display

msdn.microsoft.com/Forums/vstudio/en-US/11ddeceb-ca55-4d17-8c79-dd18104456a9/ajax-call-to-wcf-returns-400-bad-request\">文章,问题是AJAX具有跨站点限制,这会阻止您调用远程服务。对于这种情况,一个简单的解决方法是在同一个应用程序中使用服务器端代码来调用远程WCF服务的服务器端page_method(脚本回调)或本地wcf服务。您的网页使用AJAX调用本地WCF服务(其工作原理类似于中介)。另一种方法是将远程WCF服务定义为标准REST服务,它接受http GET请求。因此,您的网页可以使用JQuery API通过JQuery脚本访问远程WCF服务操作。然后,您将WCF服务托管为控制台应用程序,并在另一个Web应用程序中使用JQuery来调用它: ConsoleAJAXWCF)]
public interface IService1
{
[OperationContract]
[WebInvoke(Method =GET,ResponseFormat = WebMessageFormat.Json)]
string GetTEST ();

$ b $ [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1:IService1
{

public string GetTEST()
{
返回OKKKKKKKK;


您托管控制台应用程序:

  // program.cs 
using System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.ServiceModel;
使用System.ServiceModel.Description;
使用ConsoleAJAXWCF;

命名空间ConsoleAJAXWCF
{
class程序
{
static void Main(string [] args)
{

//第1步添加一个服务端点。
using(WebServiceHost selfHost = new WebServiceHost(typeof(Service1)))
{
try
{
//步骤2启动服务。
selfHost.Open();
Console.WriteLine(服务已准备就绪。);
Console.WriteLine(按< ENTER>终止服务。);
Console.WriteLine();
Console.ReadLine();

//关闭ServiceHostBase关闭服务。
selfHost.Close();
}
catch(CommunicationException ce)
{
Console.WriteLine(发生异常:{0},ce.Message);
selfHost.Abort();
}
}
}
}
}
// WCF配置
< endpointBehaviors>
< behavior name =AJAXEndpoint>
< webHttp />
< /行为>
< / endpointBehaviors>
< /行为>
< services>
< service name =ConsoleAJAXWCF.Service1>
behaviorConfiguration =AJAXEndpoint
address =binding =webHttpBindingcontract =ConsoleAJAXWCF.IService1>
< identity>
< dns value =localhost/>
< / identity>
< / endpoint>
<主机>
< baseAddresses>
< add baseAddress =http:// localhost:52768 / Service1 //>
< / baseAddresses>
< / host>
< / service>
< / services>

验证服务是否正常:


  1. 从Visual Studio 2012内运行ConsoleAJAXWCF控制台应用程序。在Windows Vista和更高版本的操作系统上运行时,该服务必须以管理员权限运行。因为Visual Studio是以管理员权限运行的,所以GettingStartedHost也以管理员权限运行。您还可以启动一个新的命令提示符,以管理员权限运行它,并在其中运行service.exe。

  2. 打开Internet Explorer并浏览到localhost上的服务调试页面:52768 / Service1 / / li>

在调用服务的ASPX页面中的代码:

 <!DOCTYPE html> 
< html xmlns =http://www.w3.org/1999/xhtml>
< head>
< script Language =JavaScriptsrc =Scripts / jquery-1.10.2.min.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery-1.9.1.intellisense.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.unobtrusive-ajax.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.unobtrusive-ajax.min.js>< / script>
< script Language =JavaScriptsrc =Scripts / jquery.validate.js>< / script>
< title> TESTE< / title>
< / head>
< body>
< input id =Button1type =buttonvalue =buttononclick =CallRESTWCFService()/>
< / body>
< script type =text / javascript>

函数CallRESTWCFService(){
$ .getJSON(http:// localhost:52768 / Service1 / GetTEST,{},
function(data){
警报(数据);
});
}
< / script>
< / html>


I have a WCF project in VSStudio2012 and I want to call a method from JavaScript function.

JavaScript file :

var url = 'http://localhost:52768/Service1.svc/'

function test() {

var response;

$.ajax({
    type: 'Post',
    url: url + 'GetTEST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {
        alert(msg);
    },

    error: function (e) {
        alert("Error  : " + e.statusText);
    }
});

}

HTML file :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script Language="JavaScript" src="Scripts/JavaScript1.js"></script>
<script Language="JavaScript" src="Scripts/jquery-1.10.2.min.js"></script>
<script Language="JavaScript" src="Scripts/jquery-1.9.1.intellisense.js"></script>
<script Language="JavaScript" src="Scripts/jquery-1.9.1.js"></script>
<script Language="JavaScript" src="Scripts/jquery-1.9.1.min.js"></script>
<script Language="JavaScript" src="Scripts/jquery.unobtrusive-ajax.js"></script>
<script Language="JavaScript" src="Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script Language="JavaScript" src="Scripts/jquery.validate.js"></script>
<script Language="JavaScript" src="Scripts/jquery.validate.min.js"></script>
<title>TESTE</title>
</head>
<body>
<input id="Button1" type="button" value="button" onclick="test()"/>
</body>

</html>

In my IService1.cs

    [OperationContract]
    [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json)]
    string GetTEST();

Here is that alert display

And the error :

localhost:52768/Service1.svc display

解决方案

Based on this article, the issue is that AJAX has cross-site limitation which prevents you to call remote service. For such cases, a simple workaround is define a server-side page_method (script callback) or local wcf service within the same application which use server-side code to call the remote WCF service. And your web page use AJAX to call the local WCF service (which works like an intermediary).

Another approach is defining your remote WCF service as a standard REST service which accept http GET request. Thus, your web page can use JQuery api to access the remote WCF service operation through JQuery script. You then host your WCF service as a console application and use JQuery in another web application to call it:

  [ServiceContract(Namespace="ConsoleAJAXWCF")]
  public interface IService1
  {
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    string GetTEST();
  }

  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class Service1 : IService1
  {

    public string GetTEST()
    {
      return "OKKKKKKKK";
    }
  }

You hosting console application:

// program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description; 
using ConsoleAJAXWCF;    

namespace ConsoleAJAXWCF
{
    class Program
    {
        static void Main(string[] args)
        {

            // Step 1 Add a service endpoint.
            using (WebServiceHost selfHost = new WebServiceHost(typeof(Service1)))
            {
                try
                {
                   // Step 2 Start the service.
                   selfHost.Open();
                   Console.WriteLine("The service is ready.");
                   Console.WriteLine("Press <ENTER> to terminate service.");
                   Console.WriteLine();
                   Console.ReadLine();

                   // Close the ServiceHostBase to shutdown the service.
                   selfHost.Close();
                }
                catch (CommunicationException ce)
                {
                    Console.WriteLine("An exception occurred: {0}", ce.Message);
                    selfHost.Abort();
                }                
            }            
        }
    }
}
    // WCF Configuration    
   <endpointBehaviors>
      <behavior name="AJAXEndpoint" >
       <webHttp/>
       </behavior>
     </endpointBehaviors>
    </behaviors>
    <services>
      <service name="ConsoleAJAXWCF.Service1">
        <endpoint 
         behaviorConfiguration="AJAXEndpoint" 
         address="" binding="webHttpBinding" contract="ConsoleAJAXWCF.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:52768/Service1/"/>
          </baseAddresses>
        </host>
      </service>
    </services>

Verify the service is working:

  1. Run the ConsoleAJAXWCF console application from inside Visual Studio 2012. When running on Windows Vista and later operating systems, the service must be run with administrator privileges. Because Visual Studio was run with Administrator privileges, GettingStartedHost is also run with Administrator privileges. You can also start a new command prompt running it with Administrator privileges and run service.exe within it.
  2. Open Internet Explorer and browse to the service's debug page at localhost:52768/Service1/

Code in ASPX page which calls the service:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <script Language="JavaScript" src="Scripts/jquery-1.10.2.min.js"></script>
      <script Language="JavaScript" src="Scripts/jquery-1.9.1.intellisense.js"></script>
      <script Language="JavaScript" src="Scripts/jquery.unobtrusive-ajax.js"></script>
      <script Language="JavaScript" src="Scripts/jquery.unobtrusive-ajax.min.js"></script>
      <script Language="JavaScript" src="Scripts/jquery.validate.js"></script>
      <title>TESTE</title>
   </head>
   <body>
       <input id="Button1" type="button" value="button" onclick="CallRESTWCFService()"/>
   </body>
   <script type="text/javascript">

    function CallRESTWCFService() {
      $.getJSON("http://localhost:52768/Service1/GetTEST", {},
        function (data) {
          alert(data);
        });       
    }
  </script>
</html>

这篇关于在HTML页面中用Javascript调用Wcf服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆