第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ASP.net MVC返回JSONP

ASP.net MVC返回JSONP

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

3 回答

?
鳳凰求蠱

TA貢獻1825條經(jīng)驗 獲得超4個贊

我沒有使用Jsonp()方法對控制器進行子類化,而是采用了擴展方法路線,因為它對我來說感覺更干凈。關于JsonpResult的好處是,您可以像測試JsonResult一樣完全測試它。


我做了:


public static class JsonResultExtensions

{

    public static JsonpResult ToJsonp(this JsonResult json)

    {

        return new JsonpResult { ContentEncoding = json.ContentEncoding, ContentType = json.ContentType, Data = json.Data, JsonRequestBehavior = json.JsonRequestBehavior};

    }

}

這樣,您不必擔心創(chuàng)建所有不同的Jsonp()重載,只需將您的JsonResult轉換為一個Jsonp。


查看完整回答
反對 回復 2019-12-20
  • 3 回答
  • 0 關注
  • 647 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號