繁体   English   中英

从JQuery调用WCF服务不起作用

[英]Calling WCF Service from JQuery does not work

问题是如何从JQuery访问非aspx服务。

我试过的

最简单的情况:

合同:

using System.ServiceModel;
using System.ServiceModel.Web;

namespace TheService
{
    [ServiceContract]
    public interface ITheService
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        string Get();
    }
}

服务:使用系统; 使用System.ServiceModel.Web;

namespace TheService
{
    public class TheService : ITheService
    {
        public string Get()
        {
            return "Hello, world!";
        }
    }
}

托管服务:

class Program
    {
        static void Main(string[] args)
        {
            Uri httpUrl = new Uri("http://localhost:22334/TheService");

            ServiceHost host = new ServiceHost(typeof(TheService), httpUrl);

            ServiceMetadataBehavior serviceMetaDataBehaviour = new ServiceMetadataBehavior
            {
                HttpGetEnabled = true,
                MetadataExporter = {PolicyVersion = PolicyVersion.Policy15}
            };
            host.Description.Behaviors.Add(serviceMetaDataBehaviour);

            host.AddServiceEndpoint(typeof(ITheService), new WebHttpBinding(), "");

            host.Open();

            Console.ReadLine();
        }
    }

如果我尝试使用wcftestclient访问服务,则可以访问数据。

现在我试图通过jQuery访问它

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
      $(document).ready(function() {

  $.getJSON("http://localhost:22334/TheService/Get",
  function(data){
    alert("Data Loaded: " + data);
  });
});

  </script>
</head>
<body>

</body>
</html>

我以为应该发生的事情是,我回到了Hello World。 但事实并非如此。

我试过了:

$.ajax({
    type: "GET",
    url: "http://localhost:22334/TheService/Get", 
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert(msg);
    },
    error: function(err) {
        alert(err.toString());
        if (err.status == 200) {
            ParseResult(err);
        }
        else { alert('Error:' + err.responseText + '  Status: ' + err.status); }
    }
});

而我得到的只是两个警报“ [Object] object”和“ Error:Status:0”

因此,在这种情况下,它似乎遇到了一些错误,但是在哪一个呢?

我以前从未使用过jquery,所以在哪里可以获得更多有用的错误消息?

我需要在wcf服务中定义其他内容吗?

最后,两个项目不应重复使用。 JQuery应该在客户端使用,而wcf服务则在集中式服务器上运行。

如果我改变

ServiceHost host = new ServiceHost(typeof(TheService), httpUrl);

WebServiceHost host = new WebServiceHost(typeof(ServiceCalculator), httpUrl);

我可以看到已到达WCF服务器上的调试点(返回文本)-但仍显示两个错误对话框。

(已添加:localhost:22334 / TheService / Get在浏览器中返回“ Hello World”-因此,我认为这是JQuery / Ajax的问题​​,还是?)


更新:

对应于回复和http://pranayamr.blogspot.de/2011/06/calling-cross-domain-wcf-service-using.html,我添加了以下内容:

将Debug设置为true:

ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();

if (debug == null)
{
    host.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
}
else
{
    if (!debug.IncludeExceptionDetailInFaults)
    {
        debug.IncludeExceptionDetailInFaults = true;
    }
}

将行为更改为ASP兼容性

for (int i = 0; i < host.Description.Behaviors.Count; i++)
{
    if (host.Description.Behaviors[i] is AspNetCompatibilityRequirementsAttribute)
    {
        host.Description.Behaviors.RemoveAt(i);
        break;
    }
}
host.Description.Behaviors.Add(new AspNetCompatibilityRequirementsAttribute { RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed });

允许跨域脚本访问

host.Description.Behaviors.Add(serviceMetaDataBehaviour);
WebHttpBinding binding = new WebHttpBinding {CrossDomainScriptAccessEnabled = true};
host.AddServiceEndpoint(typeof(IServiceCalculator), binding, "");

并尝试设置jsonp

$.ajax({
    type: "GET",
    url: "http://localhost:22334/TheService", 
    method: "Get",
    contentType: "application/json; charset=utf-8",
    dataType: 'jsonp',
    success: function(msg) {
        alert(msg);
    },
    error: function(err) {
        alert(err.toString());
        if (err.status == 200) {
            ParseResult(err);
        }
        else { alert('Error:' + err.responseText + '  Status: ' + err.status); }
    }
});

现在它似乎以某种方式起作用。 (如果出了什么问题,仍然没有得到真正的错误信息...)(而且似乎也不需要asp部分。)

您可能会遇到跨域请求( http://www.d-mueller.de/blog/cross-domain-ajax-guide/ )。

尝试使用CORS( http://en.wikipedia.org/wiki/Cross-origin_resource_sharing )或JSONP( http://en.wikipedia.org/wiki/JSONP )或类似的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM