我正在寻找跨域返回一些JSON,我知道这样做的方式是通过JSONP而不是纯JSON。我正在使用ASP.net MVC,所以我只想扩展JSONResult类型,然后扩展控制器,以便它也实现了Jsonp方法。这是最好的方式去做,或者有一个内置的ActionResult可能会更好?ASP.net MVC返回JSONP
编辑:我继续做了。仅供参考起见,我增加了一个新的结果:
public class JsonpResult : System.Web.Mvc.JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/javascript";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
#pragma warning disable 0618
HttpRequestBase request = context.HttpContext.Request;
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(request.Params["jsoncallback"] + "(" + serializer.Serialize(Data) + ")");
#pragma warning restore 0618
}
}
}
而且两个方法我所有控制器的父类:
protected internal JsonpResult Jsonp(object data)
{
return Jsonp(data, null /* contentType */);
}
protected internal JsonpResult Jsonp(object data, string contentType)
{
return Jsonp(data, contentType, null);
}
protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding)
{
return new JsonpResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}
就像一个魅力。
谢谢!在我们的项目中实现了这个! :) – 2010-02-01 23:47:23
不错!但JSONP应作为应用程序/ JavaScript http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp – 2011-06-07 15:17:17
另请参阅http://support.github.com/discussions/api/18 -content-type-should-applicationjavascript-for-jsonp-request http://stackapps.com/questions/1668/wrong-content-type-in-jsonp-calls – 2011-06-07 15:29:22