我怎么能生产JSONP从跨域调用ASP.NET Web服务? [英] How can I produce JSONP from an ASP.NET web service for cross-domain calls?

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

问题描述

我写了一个web服务返回JSON和我试着使用jQuery像这样来调用它:

I've written a webservice which returns JSON and I've tried to call it using jQuery like this:

$.ajax({
    contentType: "application/json; charset=utf-8",
    url: "http://examplewebsite.com/service.asmx/GetData",
    data: { projectID: 1 },
    dataType: "jsonp",
    success: function () {alert("success");}
});

然而,code从不尽管Web服务调用看着使用招的HTTP流量时取得成功调用成功功能。我想这是因为我的web服务将返回原始JSON而不是JSONP。

However the code never calls the success function, despite the webservice call being successful when looking at the HTTP traffic using Fiddler. I think this is because my web service is returning raw JSON instead of JSONP.

我怎么能生产JSONP从这样一个标准的.NET Web服务方法的响应:

How can I produce JSONP as the response from a standard .NET webservice method like this:

[WebMethod(), ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public Project GetData(int projectID)
{
    Project p = new Project();
    p.Name = "foobar";
    return p;
}

感谢。

推荐答案

好了,我终于理解了它自己。因为我发现这样很难在网上找到一个完整的工作解决方案,我已经决定要在这里记录我的工作解决方案。

OK, I've eventually figured it out myself. As I found it so hard to find a complete working solution on the web, I've decided to document my working solution here.

一个JSONP响应就是标准的JSON字符串包裹在一个函数调用。 ASP.NET似乎并没有提供任何的方式来回报这种格式的直接效应初探,但它是非常简单的做这自己。你这样做虽然,必须覆盖JSON编码的默认方法。

A JSONP response is just standard JSON string wrapped in a function call. ASP.NET doesn't seem to provide any way to return the reponse in this format directly, but it's very simple to do this yourself. You do though, have to override the default method of JSON encoding.

下面是JSONP的一个例子。

Below is an example of JSONP.

使用functionName({名称:'值';});

..现在该位:
{名称:'值';} 就是标准的JSON,任何JSON序列会给你,所以我们需要做的就是在函数调用的包装策略。不幸的是,这样做意味着我们必须无线化(或旁路),这是当你从Web服务函数返回一个对象的框架透明地处理现有的JSON编码。

..now this bit: { name: 'value';} is just standard JSON that any JSON serializer will give you, so all we need to do is tack on the function call wrapper. Unfortunately, doing that means we have to 'unwire' (or bypass) the existing JSON encoding which is handled transparently by the framework when you return an object from the web service function.

这是通过完全由写JSONP使用我们自己code中的输出流(响应)重写从Web服务功能的响应完成。这其实很简单,我已经包括下面的例子。

This is done by overriding the response from the web service function completely by writing the JSONP to the output stream (Response) using our own code. This is actually quite straightforward and I've included an example below.

您可以使用内置的<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer(v=vs.90).aspx\">DataContractJsonSerializer (在ASP.NET 3.5 +的System.Runtime.Serialization.Json命名空间)或 NewtonSoft JSON序列化,无一不例子如下所示。我preFER使用的 NewtonSoft JSON (从安装的NuGet),而不是内置JSON序列化,因为我觉得它给你更多的控制权,也可以输出调试格式良好的人类可读的JSON。它也快得多在纸上!

You can use either the built in DataContractJsonSerializer (from the System.Runtime.Serialization.Json namespace in ASP.NET 3.5+) or the NewtonSoft JSON serializer, and both examples are shown below. I prefer to use the the NewtonSoft JSON (installed from nuget) rather than the built in JSON serializer as I find it gives you more control and also can output nicely formatted human readable JSON for debugging. It's also much faster on paper!

[WebMethod()]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetData(int projectID, string callback)
{
    List<Video> videos = null;
    // <code here to populate list on line above>

    // Method 1: use built-in serializer:
    StringBuilder sb = new StringBuilder();
    JavaScriptSerializer js = new JavaScriptSerializer();
    sb.Append(callback + "(");
    sb.Append(js.Serialize(videos));
    sb.Append(");");    

    // Method 2: NewtonSoft JSON serializer (delete as applicable)
    // StringBuilder sb = new StringBuilder();
    // sb.Append(callback + "(");
    // sb.Append(JsonConvert.SerializeObject(videos, Formatting.Indented)); // indentation is just for ease of reading while testing
    // sb.Append(");");     

    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write(sb.ToString());
    Context.Response.End();
}

此方法然后可以使用下面的JQuery code名为:

This method can then be called using the following JQuery code:

$.ajax({
    crossDomain: true,
    contentType: "application/json; charset=utf-8",
    url: "http://examplewebsite.com/service.asmx/GetData",
    data: { projectID: 1 }, // example of parameter being passed
    dataType: "jsonp",
    success: onDataReceived
});

function onDataReceived(data)
{
    alert("Data received");
    // Do your client side work here.
    // 'data' is an object containing the data sent from the web service 
    // Put a JS breakpoint on this line to explore the data object
}

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

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