简体   繁体   English

从JQuery调用WCF服务不起作用

[英]Calling WCF Service from JQuery does not work

Problem is how to access a non aspx service from JQuery. 问题是如何从JQuery访问非aspx服务。

What i have tried: 我试过的

Easiest case: 最简单的情况:

Contract: 合同:

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

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

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

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

Hosting the service: 托管服务:

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();
        }
    }

If i try to access the service with the wcftestclient, i can access the data. 如果我尝试使用wcftestclient访问服务,则可以访问数据。

Now i tried to access it via jquery 现在我试图通过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>

What I assumed that should happen is that I get a Hello world back. 我以为应该发生的事情是,我回到了Hello World。 but it doesn't. 但事实并非如此。

I tried: 我试过了:

$.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); }
    }
});

and all i got was two alerts "[Object] object" and "Error: Status: 0" 而我得到的只是两个警报“ [Object] object”和“ Error:Status:0”

So in this case it seems that it runs into some error, but in which? 因此,在这种情况下,它似乎遇到了一些错误,但是在哪一个呢?

I have never used jquery before, so is there any where to get a little bit more helpful error message? 我以前从未使用过jquery,所以在哪里可以获得更多有用的错误消息?

Do I need to define anything else in the wcf service? 我需要在wcf服务中定义其他内容吗?

At the end both projects should not be in the same aplication. 最后,两个项目不应重复使用。 the JQuery should be used at a client side and the wcf service run at a centralized server. JQuery应该在客户端使用,而wcf服务则在集中式服务器上运行。

If i change 如果我改变

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

to

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

i can see that a debug point at the WCF server is reached (return of the text) - but still both error dialogs are show. 我可以看到已到达WCF服务器上的调试点(返回文本)-但仍显示两个错误对话框。

(Added: localhost:22334/TheService/Get returns "Hello World" in browser - therefore i think it is either a problem with JQuery/Ajax, or ? ) (已添加:localhost:22334 / TheService / Get在浏览器中返回“ Hello World”-因此,我认为这是JQuery / Ajax的问题​​,还是?)


Update: 更新:

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

Set Debug to true: 将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;
    }
}

change behaviour to asp compatibility 将行为更改为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 });

allow crossdomainscriptaccess 允许跨域脚本访问

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

and tried to set jsonp 并尝试设置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); }
    }
});

Now it seems to work somehow. 现在它似乎以某种方式起作用。 (Still getting no real error information if something goes wrong...) (and the asp part does not seem to be needed also..) (如果出了什么问题,仍然没有得到真正的错误信息...)(而且似乎也不需要asp部分。)

You might have run into a cross-domain request ( http://www.d-mueller.de/blog/cross-domain-ajax-guide/ ). 您可能会遇到跨域请求( http://www.d-mueller.de/blog/cross-domain-ajax-guide/ )。

Try CORS ( http://en.wikipedia.org/wiki/Cross-origin_resource_sharing ) or JSONP ( http://en.wikipedia.org/wiki/JSONP ) or something of the like. 尝试使用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