NetCore MVC 中如何實現JSONP格式的返回

在jquery ajax請求中,有時候設計到跨域,我們需要採用JSONP的格式進行處理,服務端也需要返回 callback 等內容

但是在MVC中,默認只有JsonResult 的返回類型,沒有支持JSONP的。

這時候我們有以下 2種方案,實現我們JSONP 格式返回的需求。

第一種方案,也是最簡單的方案:

採用ContentResult 返回,代碼如下:

 public ContentResult Test2(string callback)
        {
            var data = new { code = 2 };
            string str = callback + "(" + Newtonsoft.Json.JsonConvert.SerializeObject(data) + ")";
            return new ContentResult() { Content = str, ContentType = "application/json" };
        }

 

第二種方案呢,我們自己寫一個JSONP 類的擴展,代碼如下:

    public class JsonpResult : Microsoft.AspNetCore.Mvc.JsonResult
    {
        //
        // 摘要:
        //     Creates a new Microsoft.AspNetCore.Mvc.JsonResult with the given value.
        //
        // 參數:
        //   value:
        //     The value to format as JSON.
        public JsonpResult(object value) : base(value) { }
        //
        // 摘要:
        //     Creates a new Microsoft.AspNetCore.Mvc.JsonResult with the given value.
        //
        // 參數:
        //   value:
        //     The value to format as JSON.
        //
        //   serializerSettings:
        //     The serializer settings to be used by the formatter.
        //     When using System.Text.Json, this should be an instance of System.Text.Json.JsonSerializerOptions.
        //     When using Newtonsoft.Json, this should be an instance of JsonSerializerSettings.
        public JsonpResult(object value, object serializerSettings) : base(value, serializerSettings) { }
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override void ExecuteResult(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            //獲取callback
            string callback = context.HttpContext.Request.Query["callback"];
            string result = string.Empty;
            if (SerializerSettings is Newtonsoft.Json.JsonSerializerSettings)
            {
                if (SerializerSettings != null)
                {
                    var setting = SerializerSettings as Newtonsoft.Json.JsonSerializerSettings;
                    result = Newtonsoft.Json.JsonConvert.SerializeObject(Value, settings: setting);
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.SerializeObject(Value);
                }
            }
            else
            {
                if (SerializerSettings != null)
                {
                    var setting = SerializerSettings as System.Text.Json.JsonSerializerOptions;
                    result = System.Text.Json.JsonSerializer.Serialize(Value, options: setting);
                }
                else
                {
                    result = System.Text.Json.JsonSerializer.Serialize(Value);
                }

            }
            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.WriteAsync(callback + "(" + result + ")");
        }

        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            //獲取callback
            string callback = context.HttpContext.Request.Query["callback"]; //這邊是固定了callback名稱,若不固定,可定義參數傳進來
            string result = string.Empty;
            if (SerializerSettings is Newtonsoft.Json.JsonSerializerSettings)
            {
                if(SerializerSettings!=null)
                {
                    var setting = SerializerSettings as Newtonsoft.Json.JsonSerializerSettings;
                        result = Newtonsoft.Json.JsonConvert.SerializeObject(Value,settings:setting);
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.SerializeObject(Value);
                }
            }
            else
            {
                if (SerializerSettings != null)
                {
                    var setting = SerializerSettings as System.Text.Json.JsonSerializerOptions;
                    result = System.Text.Json.JsonSerializer.Serialize(Value, options: setting);
                }
                else
                {
                    result = System.Text.Json.JsonSerializer.Serialize(Value);
                }
               
            }
            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.WriteAsync(callback + "(" + result + ")");
            return Task.CompletedTask;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override string ToString()
        {
            return base.ToString();
        }
    }

以上,我們就完成了擴展,然後應用如下:

      public JsonpResult Test()
        {
            var data = new { code = 1 };
            return new JsonpResult(new { code = 1 });
        }

這樣,我們也可以完成jsonp格式的返回處理了。

若是要像Json(數據),這樣調用的,直接定義個基類控制器,然後業務控制器繼承該基類控制器即可。如

    public class JsonpBaseController : Controller
    {
        public JsonpResult Jsonp(object data)
        {
            return new JsonpResult(data);
        }
    }

然後 做些繼承:    public class HomeController : JsonpBaseController

就可以直接使用了

      public JsonpResult Test()
        {
            var data = new { code = 1 };
            return Jsonp(data);
        }

===================================

更多分享,請大家關注我的個人公衆號:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章