1. 程式人生 > 其它 >NetCore MVC 中如何實現JSONP格式的返回

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);
        }

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

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