我正在尋找跨域返回一些JSON的方式,并且我知道這樣做的方法是通過JSONP而非純JSON。我使用的是ASP.net MVC,因此我在考慮只擴(kuò)展JSONResult類型,然后擴(kuò)展ig Controller,以便它也實(shí)現(xiàn)了Jsonp方法。這是最好的解決方法,還是有內(nèi)置的ActionResult可能更好?編輯:我繼續(xù)這樣做。僅供參考,我添加了一個(gè)新結(jié)果: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 }; }奇跡般有效。
ASP.net MVC返回JSONP
呼喚遠(yuǎn)方
2019-12-20 10:10:52