跨域调用与jQuery JSONP到ASP.NET Web服务 [英] cross domain call with jQuery jsonp to ASP.NET web service

查看:146
本文介绍了跨域调用与jQuery JSONP到ASP.NET Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是已知的问题,并讨论<一个href=\"http://bloggingabout.net/blogs/adelkhalil/archive/2009/08/14/cross-domain-jsonp-with-jquery-call-step-by-step-guide.aspx\"相对=nofollow>这里和的这里
但即使是阅读和实施建议的解决方案后,我无法使这项工作。

My problem is known issue and discussed here and here. But even after reading and implementing the suggested solutions i am unable to make this work.

问题:Web服务返回的XML insted的JSON的:

The problem: the web service returning xml insted of json:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string>

现在可以突破code段:

Now lets break the code into sections:

远程服务器(IIS 7.0,.NET 4):
结果
web.config中:

THE REMOTE SERVER (IIS 7.0, .NET 4):
web.config:

<?xml version="1.0"?>
<configuration>
        <system.webServer>
            <modules>
                <add name="JsonHttpModule.JsonHttpModule" type="JsonHttpModule"/>
            </modules>
        </system.webServer>
    <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="102400"/>
            </webServices>
        </scripting>
    </system.web.extensions>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <customErrors mode="Off"/>
        <webServices>
            <protocols>
                <add name="HttpGet"/>
                <add name="HttpPost"/>
            </protocols>
        </webServices>
    </system.web>
</configuration>

结果
Web服务


the web service:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using JsonHttpModule;
/// <summary>
/// Summary description for JSONP_EndPoint
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string Sum(string x, string y)
    {
        return x + y;
    }

}

结果

在HTTP模块类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

/// <summary>
/// Summary description for ContentTypeHttpModule
/// </summary>
namespace JsonHttpModule
{
    public class JsonHttpModule : IHttpModule
    {
        private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8";

        public void Dispose()
        {
        }
        public void Init(HttpApplication app)
        {
            app.BeginRequest += OnBeginRequest;
            app.EndRequest += new EventHandler(OnEndRequest);
        }
        public void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = app.Request;
            //Make sure we only apply to our Web Service
            if (request.Url.AbsolutePath.ToLower().Contains("MyService.asmx"))
            {
                if (string.IsNullOrEmpty(app.Context.Request.ContentType))
                {
                    app.Context.Request.ContentType = JSON_CONTENT_TYPE;
                }
                app.Context.Response.Write(app.Context.Request.Params["callback"] + "(");
            }
        }
        void OnEndRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = app.Request;
            if (request.Url.AbsolutePath.ToLower().Contains("MyService.asmx"))
            {
                app.Context.Response.Write(")");
            }
        }
    }
}

客户端(本地主机):
结果

<script>
    $(function () {
        $('#btn_test').click(function () {
            $.ajax({ url: "http://tonofweb.com/MyService.asmx/Sum",
                data: { x: JSON.stringify("Now i am getting jsop string"), y: JSON.stringify("2nd param") },
                dataType: "jsonp",
                success: function (json) {
                    alert(json.d);
                },
                error: function () {
                    alert("Hit error fn!");
                }
            });
    });
});
</script>
    <input id="btn_test" type="button" value="POST" />

所以我在做什么错在这里?
你可以测试它自己是一个活的Web服务。
谢谢你的帮助。

so what am i doing wrong here? you can test it yourselves it's a live web service. Thank you for your help.

推荐答案

这似乎所有的配置和属性到位Web服务返回JSON,但我在你的jQuery的要求也注意到,你是不是指定的内容类型你正在传递数据我已经把它添加到下面的code:

It seems all the configuration and attributes are in place for the web service to return JSON but I did notice in your jQuery request, you are not specifying the content type of the data you are passing in. I have added it to the code below:

$.ajax({
  url: "http://tonofweb.com/MyService.asmx/Sum",
  contentType: "application/json; charset=utf-8",
  data: { x: JSON.stringify("1"), y: JSON.stringify("2") },
  dataType: "jsonp",
  success: function (json) {
    alert(json.d);
  },
  error: function () {
    alert("Hit error fn!");
  }
});

通知我添加的contentType:应用/ JSON的;字符集= UTF-8,来的要求设置。

我已经浏览到 http://tonofweb.com (这在目前返回一个403),包括测试这code使用jQuery的 jQuerify书签,然后运行从code你的问题第一个( contentType中),然后在code我张贴以上(将contentType)。

I have tested this code by browsing to http://tonofweb.com (which returns a 403 at the moment), including jQuery using the jQuerify bookmarklet, and then running the code from your question first (without the contentType), and then the code I posted above (with the contentType).

下面是从网络选项卡中的Chrome开发者工具的反应:

Here are the responses from the Network tab in the Chrome Developer Tools:

如果没有的contentType

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string>

随着的contentType

{"d":"12"}

所以,至少导致JSON第二个从服务器返回。因此,所有其他条件相同,我会说添加的contentType。

So the second one at least results in JSON being returned from the server. So all else being equal, I'd say add the contentType.

在这里看到的要求作出解释返回JSON:

See here for an explanation of the requirements to return JSON:

ASMX和JSON -

HTTP请求必须声明的内容类型的应用程序/ JSON的。这个
  通知ScriptService它将接收其参数JSON
  并应以实物回应。

The HTTP request must declare a content-type of application/json. This informs the ScriptService that it will receive its parameters as JSON and that it should respond in kind.

现在你还有一个问题,那就是请求,完成后,话费误差函数。如果您更改数据类型:JSONP数据类型:JSON它会调用成功功能。因此,一些关于你实现回调包装是错误的,因为jQuery无法处理响应为JSONP。

Now you still have another problem, and that is that the request, upon completion, calls the error function. If you change dataType: "jsonp" to dataType: "json" it will call the success function. So something about your implementation of the callback wrapper is wrong, because jQuery can't handle the response as JSONP.

现在我没有看到包裹在响应无论是为JSONP回调,响应应该是这样的:

Now I'm not seeing the callback wrapped in the response either, for JSONP, the response should be something like:

jQuery17106476630216930062_1326752446188({"d":"12"})

我注意到你链接到<一个href=\"http://bloggingabout.net/blogs/adelkhalil/archive/2009/08/14/cross-domain-jsonp-with-jquery-call-step-by-step-guide.aspx\">this帖子有关如何执行从Web服务的JSONP响应,但你不继的建议:不要使用 Response.Filter ,而是使用的Response.Write

I notice you are linking to this post about how to do a JSONP response from a web service, but you are not following the advice: you don't use Response.Filter, instead you use Response.Write.

这篇关于跨域调用与jQuery JSONP到ASP.NET Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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