使用 JQuery 访问 ASP.net Web 服务时出错 - JSONP

发布于 2024-07-15 02:02:39 字数 2799 浏览 4 评论 0原文

请查看下面的代码并帮助我找出我的网络服务代码中做错了什么。 我想设置一个可以使用 JSONP 来使用的 asp.net Web 服务。 我在客户端使用 Jquery 来访问该网站。 即使设置了正确的属性后,我的 Web 服务仍然会发出 xml,导致 aynch 调用失败。

Web 服务

[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 服务响应:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">test({message: 'Hello World'})</string>

Web.Config:

<webServices>
    <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
    </protocols>
</webServices>
<httpHandlers>
    <remove verb="*" path="*.asmx"/>
    <add verb="*" path="*.asmx" validate="false" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
            System.Web.Extensions, Version=3.5.0.0, 
            Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add verb="*" path="*_AppService.axd" validate="false" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
            System.Web.Extensions, Version=3.5.0.0, 
            Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add verb="GET,HEAD" path="ScriptResource.axd" 
        type="System.Web.Handlers.ScriptResourceHandler, 
            System.Web.Extensions, Version=3.5.0.0, 
            Culture=neutral, PublicKeyToken=31BF3856AD364E35" 
        validate="false"/>
</httpHandlers>
<httpModules>
    <add name="ScriptModule" 
        type="System.Web.Handlers.ScriptModule, System.Web.Extensions, 
            Version=3.5.0.0, Culture=neutral, 
            PublicKeyToken=31BF3856AD364E35"/>
</httpModules>

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 服务失败。

Please look at the code below and help me to figure out what am I doing wrong in my web service code. I want to set up an asp.net web service that can be consumed using an JSONP. I am using Jquery at client side to access the site. Even after setting up proper attributes my web service still emits xml due to which the aynch call fails.

Web Service

[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 Service Response:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">test({message: 'Hello World'})</string>

Web.Config:

<webServices>
    <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
    </protocols>
</webServices>
<httpHandlers>
    <remove verb="*" path="*.asmx"/>
    <add verb="*" path="*.asmx" validate="false" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
            System.Web.Extensions, Version=3.5.0.0, 
            Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add verb="*" path="*_AppService.axd" validate="false" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
            System.Web.Extensions, Version=3.5.0.0, 
            Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add verb="GET,HEAD" path="ScriptResource.axd" 
        type="System.Web.Handlers.ScriptResourceHandler, 
            System.Web.Extensions, Version=3.5.0.0, 
            Culture=neutral, PublicKeyToken=31BF3856AD364E35" 
        validate="false"/>
</httpHandlers>
<httpModules>
    <add name="ScriptModule" 
        type="System.Web.Handlers.ScriptModule, System.Web.Extensions, 
            Version=3.5.0.0, Culture=neutral, 
            PublicKeyToken=31BF3856AD364E35"/>
</httpModules>

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

    }

});

The js code works with an handler, but fails for the webservice due to xml response.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独患者 2024-07-22 02:02:40

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

我尝试了您的示例并观看了 Fiddler 中的请求/响应交换,果然我没有看到内容类型:application/xml; charset=UTF-8 在 HTTP GET 请求的标头中发送。 如果使用 HTTP POST,则标头会被发送。 我猜测此标头的存在是 ASP.NET Web 服务管道决定是否返回 JSON 或 XML 格式的响应的提示。

看来您不是唯一一个遇到此问题的人,请参阅 Elegant Code 网站上的以下文章:

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

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

  • 使用 HttpModule 注入 Content-Type: application/xml; charset=UTF-8 标头添加到请求流中,如上面的文章所述。

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

  • 尝试 Rick Strahl 的基于页面的方法
    在下面的文章中(其中
    无论如何,实际上是一个 HttpHandler): JSONP for cross -site Callbacks.

I think the problem here is because jQuery doesn't set the Content-Type header in the HTTP request for HTTP GET's when using $.ajax(). It only gets sent if the request type is 'POST'. This seems to be the case for both dataType: "jsonp" and dataType: "json".

I tried your example and watched the request/response exchange in Fiddler and sure enough I don't see Content-Type: application/xml; charset=UTF-8 being sent in the headers for HTTP GET requests. The header does get sent if using HTTP POST. I'm guessing the presence of this header is a cue for the ASP.NET web service plumbing to decide whether to return either a JSON or XML formatted response.

It seems you're not the only one with this problem, see the following article on the on Elegant Code website:

Calling Remote ASP.NET Web Services from JQuery

The solution appears to be one of the following:

  • Use a HttpModule to inject the Content-Type: application/xml; charset=UTF-8 header into the request stream as described in the article above.

  • Use a HttpHandler for the endpoint as you explained you were doing prior to using an ASP.NET web service.

  • Try Rick Strahl's page based approach
    in the following article (which
    is in effect a HttpHandler anyway): JSONP for cross-site Callbacks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文