jquery - 使用 jQuery jsonp 跨域调用 ASP.NET Web 服务

标签 jquery asp.net web-services cross-domain jsonp

我的问题是已知问题并已讨论 herehere 。 但即使在阅读并实现了建议的解决方案之后,我也无法完成这项工作。

问题:Web 服务返回 xml 而不是 json:

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

现在让我们将代码分成几个部分:

远程服务器(IIS 7.0、.NET 4):
网络配置:

<?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>


网络服务:

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

}


HttpModule 类:

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 服务返回 JSON,但我确实注意到在您的 jQuery 请求中,您没有指定传入数据的内容类型。我已将其添加到代码如下:

$.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: "application/json; charset=utf-8", 添加到请求设置中。

我通过浏览 http://tonofweb.com 测试了这段代码(目前返回 403),包括使用 jQuerify bookmarklet 的 jQuery ,然后首先运行您的问题中的代码(不带 contentType),然后运行我上面发布的代码( contentType)。

以下是 Chrome 开发者工具中“网络”选项卡的响应:

没有 contentType:

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

内容类型:

{"d":"12"}

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

请参阅此处了解返回 JSON 的要求的说明:

ASMX and JSON – Common mistakes and misconceptions

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.

现在还有另一个问题,那就是请求完成后调用错误函数。如果将 dataType: "jsonp" 更改为 dataType: "json" 它将调用 success 函数。所以你的回调包装器的实现是错误的,因为 jQuery 无法将响应作为 JSONP 处理。

现在我也没有看到响应中包含的回调,对于 JSONP,响应应该类似于:

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

我注意到您正在链接到 this post关于如何从 Web 服务执行 JSONP 响应,但您没有遵循建议:您不使用 Response.Filter,而是使用 Response.Write。

关于jquery - 使用 jQuery jsonp 跨域调用 ASP.NET Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884928/

相关文章:

javascript - 通过javascript函数调用asp.net传递ID

c# - 如何检查 Page.Cache 的大小?

mysql - 连接服务器上的数据库的最佳方法是什么?

javascript - Firefox 中的本地存储

jquery - 在一个 div 或 post 中随机更改指定元素的颜色

asp.net - 我如何从进程中慢慢迁移到使用 Redis 作为 session 状态提供程序?

c# - 如何解析从文件加载的 soap 消息?

c# - HttpClient GetAsync 失败

javascript - 我如何修复复选框内部

javascript - 如何将此 JSON 从 PHP 转换为 Javascript 数组