JSONP 和 ASMX 网络服务
Posted
技术标签:
【中文标题】JSONP 和 ASMX 网络服务【英文标题】:JSONP & ASMX Web Service 【发布时间】:2012-12-02 18:48:18 【问题描述】:我正在努力弄清楚如何使用 jQuery 对 ASMX Web 服务进行 JSONP 调用。这些只是我已经阅读但没有找到任何解决方案的一些页面:
How to call external webservice using jquery "jsonp"?
Posting cross-domain JSON to ASP.NET with jQuery
Error while accessing ASP.net webservice using JQuery - JSONP
Set Headers with jQuery.ajax and JSONP?
http://www.codeproject.com/Articles/43038/Accessing-Remote-ASP-NET-Web-Services-Using-JSONP
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
等等……
这是我的示例 .NET Web 方法:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetEmployee(string employeeId, string callback)
// Get the employee object from the Factory.
Employee requestedEmployee = EmployeeFactory.GetEmployee(employeeId);
if(requestedEmployee != null)
// Return the padded JSON to the caller.
CrossDomainUtility.SendJsonP(callback, requestedEmployee.ToJson());
这里是 SendJsonP():
public static void SendJsonP(string callback, string json)
// Clear any response that has already been prepared.
HttpContext.Current.Response.Clear();
// Set the content type to javascript, since we are technically returning Javascript code.
HttpContext.Current.Response.ContentType = "application/javascript";
// Create a function call by wrapping the JSON with the callback function name.
HttpContext.Current.Response.Write(String.Format("0(1)", callback, json));
// Complete this request, to prevent the ASMX web service from doing anything else.
HttpContext.Current.ApplicationInstance.CompleteRequest();
这里是一些示例 jquery 代码:
$.ajax(
url: 'http://devserver/service/service.asmx/GetEmployee',
dataType: 'jsonp',
contentType: 'application/json',
data: employeeId: '123456789'
);
我使用 [ScriptService] 装饰了 Web 服务,并且我的 web.config 配置为使用 ScriptHandlerFactory 处理 *.asmx。
我尝试过使用 ASMX 在 Content-Type 为“application/json”时使用的内置 JSON 序列化,但有几个问题:由于需要填充,它不能用于 JSONP包裹在 .NET 不支持的 JSON 上。它也不起作用,因为为了序列化 JSON,ASMX 需要一个 'ContentType: application/json' 标头,但 jQuery 在发送 GET 请求时会忽略 ContentType 标头(可能是因为它不发送任何内容)。我尝试在 Global.asax Application_BeginRequest() 中设置 Request.ContentType = "application/json" 但这没有做任何事情。我还尝试使用 beforeSend() 在 jQuery 中设置请求标头,但没有成功。
因此,由于我无法使用内置的 .NET 管道轻松地使其工作,因此我采用了自己的技术来执行对响应主体的原始写入(因此使用了 SendJsonP() 方法)。不过我仍然遇到问题,因为即使 GetEmployee() Web 方法没有返回值,.NET 也会引发序列化错误,因为它试图将对象序列化为 XML,因为我无法传递“应用程序”的 ContentType /json' 带有 GET 请求。
所以,由于无论我做什么都无法让 jQuery 添加 ContentType,我想通过使用 Fiddler2 创建手动请求来测试我的 Web 服务:
GET http://devserver/service/service.asmx/GetEmployee?callback=createMember&memberId=123456789
User-Agent: Fiddler
Content-Type: application/json
Host: devserver
...它给出了以下错误,因为我的参数不是 JSON:
"Message":"Invalid JSON primitive: createMember [....]
毕竟,我还有几个问题:
有没有办法使用内置的 .NET 序列化将填充应用于 JSON 并将其返回给客户端?
既然看起来我必须自己动手,那么在将带有参数的 JSONP 查询发送到 ASMX 页面时,我的查询字符串应该是什么样子?它必须是 JSON 格式,但我尝试了以下并收到“无效的 JSON 原语”错误:
GetEmployee?callback:"createMember", memberId:"99999999"
GetEmployee?callback=callback:"createMember"&memberId=memberId:"123456789"
有没有办法让 jQuery 发送带有 JSONP GET 请求的 ContentType 标头?
【问题讨论】:
为什么要用jsonp?你试过 json 吗? 需要克服同域源策略。 如果有帮助请查看:***.com/questions/758879/asp-net-mvc-returning-jsonp Jai:谢谢,但我需要使用长期存在的 ASMX Web 服务。我遇到的问题是特定于 ASMX 的序列化。 John:无需详述所有细节,请理解我必须坚持使用当前的 ASMX Web 服务。它庞大、复杂,并且支持我们的许多企业流程。目前重新设计解决方案是不可行的。 【参考方案1】:我刚刚决定手动处理 JSONP 请求。在我的解决方案中,用户必须通过 GET 请求提供两个查询字符串参数,以表明他们想要 JSONP 结果:callback=callbackFunctionName 和 jsonp=true。如果这两个都收到了,我将手动处理它,否则请求将继续发送到标准 ASMX 处理器。
我创建了一个新的 JsonPUtility 帮助器类,我已将其作为调用添加到 HttpApplication.BeginRequest 事件中:
public class Global : System.Web.HttpApplication
protected void Application_BeginRequest(object sender, EventArgs e)
// Requests for JSONP requests must be handled manually due to the limitations of JSONP ASMX.
JsonPUtility.ProcessJsonPRequest();
这里是 JsonPUtility 类:
/*
* JSON is Javascript Object Notation, a standard way of serializing objects in Javascript and
* other languages. For more information see http://www.json.org/.
*
* JSONP is a technique to enable the execution of Javascript that resides in a different domain. It
* works by exploiting the exception granted to the <script> tag which allows content to be loaded
* from a different domain. By contrast, making "regular" AJAX calls to a different domain will
* not work, usually throwing an "Access Denied" or "No Transport" error.
*
* JSONP (the "P" stands for "Padding") is regular JSON wrapped in a Javascript function call (the
* "Padding"). Take for example this standard JSON object:
* "Name" : "John", "Age" : 14, "Gender" : "Male"
*
* JSONP will turn that JSON into a valid Javascript function call by using the JSON as an argument
* to the callback function provided by the caller. For example, if the caller provides a callback
* value of 'processResults', the resulting JSONP looks like this:
* processResults( "Name" : "John", "Age" : 14, "Gender" : "Male" );
*
* The processResults() function will then be able to use the JSON object just like a regular object.
* Note that the callback function must be implemented on the page that receives the JSONP, otherwise
* a standard Javascript error will occur.
*
* The real "trick" to cross-domain script execution is dynamically creating a "script" tag on the
* client for every JSONP request, using the web service URL as the "src" attribute. This will cause
* the browser to automatically download and execute the script that is loaded from the URL,
* effectively bypassing the same-domain origin policy.
*/
public static class JsonPUtility
/*
* SendJsonP(string callback, string json)
*
* This method takes the provided 'json' string, wraps it so that it is a parameter to the 'callback'
* function, clears any existing response text, writes the resulting Javascript code to the
* response, and ends the response.
*
* For example, given these two parameters...
* callback = "callbackFunction"
* json = " 'FOO': 'BAR', 'JOO': 'MAR' "
*
* ... the following code is returned to the client in an HTTP response with a content-type of
* 'application/javascript':
* callbackFunction( 'FOO': 'BAR', 'JOO': 'MAR' );
*
*/
public static void SendJsonP(string callback, string json)
// Clear any response that has already been prepared.
HttpContext.Current.Response.Clear();
// Set the content type to javascript, since we are technically returning Javascript code.
HttpContext.Current.Response.ContentType = "application/javascript";
// Create a function call by wrapping the JSON with the callback function name.
HttpContext.Current.Response.Write(String.Format("0(1);", callback, json));
// Complete this request, to prevent the ASMX web service from doing anything else.
HttpContext.Current.ApplicationInstance.CompleteRequest();
/*
* bool IsJsonPRequest()
*
* Determines whether or not the current request is for JSONP javascript code.
*
* This is the criteria for making a JSONP request to this web service:
* 1. Include the jsonp parameter. Its value is not important - we recommend using jsonp=true
* to increase clarity.
* 2. Include the callback=string parameter so we know what function call to wrap around
* the requested JSON.
*/
public static bool IsJsonPRequest()
// Store the context to the current request.
var request = HttpContext.Current.Request;
// If a 'jsonp' or a 'callback' parameter was not provided, this isn't a JSONP request.
if (request.QueryString["jsonp"] == null || String.IsNullOrEmpty(request.QueryString["callback"]))
return false;
// Since both parameters were provided, this is a jsonp request.
return true;
/*
* ProcessJsonPRequest()
*
* Manual processing is required for JSONP requests due to limitations in ASMX web services.
*/
public static void ProcessJsonPRequest()
// If this isn't a JSONP request, simply return and continue regular request processing.
if (!IsJsonPRequest())
return;
// Store the context to the HTTP request.
var request = HttpContext.Current.Request;
// Store the callback function that will be wrapped around the JSON string.
string callback = request.QueryString["callback"];
// Create a place to store the object that will be serialized into JSON.
object objectForJson = null;
// Store the web service method name that is being requested. It is always going to follow the
// final slash after the .asmx extension, and will continue until the question mark that marks
// the query string.
int methodNameStartIndex = request.RawUrl.ToUpper().IndexOf(".ASMX/") + 6;
int methodNameLength = (request.RawUrl.IndexOf("?")) - methodNameStartIndex;
string requestMethod = request.RawUrl.Substring(methodNameStartIndex, methodNameLength);
// Create a place to store the string ID of the object that is going to be looked-up.
string lookupId = null;
// Based on the request URL, figure out the method that will create a reference for the objectForJson variable.
switch (requestMethod)
case "GetEmployee":
// Get the employee's ID from the query string.
lookupId = request.QueryString["employeeId"];
// If the employee ID was provided, get a Employee object.
if (!String.IsNullOrEmpty(lookupId))
objectForJson = Factory.GetEmployee(lookupId);
break;
case "GetManager":
// Get the manager's ID from the query string.
lookupId = request.QueryString["managerId"];
// If the manager ID was provided, get a Manager object.
if (!String.IsNullOrEmpty(lookupId))
objectForJson = Factory.GetManager(lookupId);
break;
case "GetOrder":
// Get the order ID from the query string.
lookupId = request.QueryString["orderId"];
// If the order ID was provided, get the object.
if (!String.IsNullOrEmpty(lookupId))
objectForJson = Factory.GetOrder(lookupId);
break;
default:
// If the request method wasn't handled, throw an exception.
throw new ArgumentException("Unknown request method '" + requestMethod + "'.");
// Create a .NET framework object to serialize the object into JSON.
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
// Serialize the object into JSON. If objectForJson is null, the callback function will be passed a parameter of null (e.g. callback(null)).
string json = jsonSerializer.Serialize(objectForJson);
// Send the JSONP string back to the caller.
SendJsonP(callback, json);
我希望这可以帮助将来的人。
谢谢, 文斯
【讨论】:
以上是关于JSONP 和 ASMX 网络服务的主要内容,如果未能解决你的问题,请参考以下文章
有没有办法限制对 ASMX Web 服务的访问,即 asmx 页面及其 WSDL?