使用JQuery访问ASP.net webservice时出错 – JSONP

请查看下面的代码,并帮助我弄清楚我的Web服务代码中出了什么问题。 我想建立一个可以使用JSONP使用的asp.net Web服务。 我在客户端使用Jquery来访问该站点。 即使在设置了适当的属性后,我的Web服务仍然会发出xml,因为aynch调用失败了。

网络服务

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { public WebService () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] [ScriptMethod(ResponseFormat= ResponseFormat.Json, XmlSerializeString=false, UseHttpGet=true)] public string HelloWorld(int id, string __callback) { return __callback + "({message: 'Hello World'})"; } } 

Web服务响应:

  test({message: 'Hello World'}) 

Web.Config中:

                

使用Javascript

 $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", url: "http://localhost:54404/jsonp/webservice.asmx/HelloWorld?id=2&__callback=?", //?jsonp=MatchSvcCallback dataType: "jsonp", data: {}, //jsonp : "MatchSvcCallback", success: function(msg) { alert("Inside success callback function"); // not being called }, error: function(xhr, msg){ var response = JSON.parse(xhr.responseText); } }); 

js代码与处理程序一起使用,但由于xml响应而导致web服务失败。

我认为这里的问题是因为当使用$.ajax()时,jQuery没有在HTTP GET的HTTP请求中设置Content-Type头。 只有在请求类型为“POST”时才会发送它。 这似乎是dataType: "jsonp"dataType: "json"

我试过你的例子,看着Fiddler中的请求/响应交换,果然我看不到Content-Type: application/xml; charset=UTF-8 Content-Type: application/xml; charset=UTF-8在HTTP GET请求的标头中发送Content-Type: application/xml; charset=UTF-8 。 如果使用HTTP POST,则会发送标头。 我猜这个标头的存在是ASP.NET Web服务管道的一个提示,决定是否返回JSON或XML格式的响应。

看来你不是唯一有这个问题的人,请参阅关于优雅代码网站的以下文章:

从JQuery调用远程ASP.NET Web服务

解决方案似乎是以下之一:

  • 使用HttpModule注入Content-Type: application/xml; charset=UTF-8 Content-Type: application/xml; charset=UTF-8标头进入请求流,如上文所述。

  • 正如您在使用ASP.NET Web服务之前所解释的那样,为端点使用HttpHandler

  • 在下面的文章中尝试Rick Strahl的基于页面的方法(无论如何实际上是HttpHandler ): 用于跨站点回调的JSONP 。