总是有人会遇到跨域问题,然后有个jsonp的解决方案,MVC中代码如下:
public class JsonpResult : System.Web.Mvc.JsonResult ???{ ???????object data = null; ???????public JsonpResult() ???????{ ???????} ???????public JsonpResult(object data) ???????{ ???????????this.data = data; ???????} ???????public override void ExecuteResult(ControllerContext controllerContext) ???????{ ???????????if (controllerContext != null) ???????????{ ???????????????HttpResponseBase Response = controllerContext.HttpContext.Response; ???????????????HttpRequestBase Request = controllerContext.HttpContext.Request; ???????????????string callbackfunction = Request["callback"]; ???????????????if (string.IsNullOrEmpty(callbackfunction)) ???????????????{ ???????????????????throw new Exception("Callback function name must be provided in the request!"); ???????????????} ???????????????Response.ContentType = "application/x-javascript"; ???????????????if (data != null) ???????????????{ ???????????????????JavaScriptSerializer serializer = new JavaScriptSerializer(); ???????????????????Response.Write(string.Format("{0}({1});", callbackfunction, serializer.Serialize(data))); ???????????????} ???????????} ???????} ???}
理论上还可以自己扩展json的解析方式,比如你觉得默认的json解析器太慢什么的。
MVC上的jsonp扩展,解决跨域访问问题
原文地址:https://www.cnblogs.com/RainbowInTheSky/p/9034584.html