自定義JsonResult其實就是利用了過濾器來實現的,過濾器的概念其實跟.net framework中差不多,不明白的可以去補習下相關知識點。
爲什麼要自定義JsonResult呢,因爲mvc 要把json序列化都通過Newtonsoft來實現,之前在.net framework也是這麼來操作的,因爲.net自帶的序列化方法對日期格式顯示並不是我們要的格式,當然也可以用其他方法來實現如自定義日期格式
這邊要特別說明下,之前在.net framework中如果HttpGet返回JsonResult時需要加上JsonRequestBehavior.AllowGet這麼一句話,而在.net core下沒有此方法了,那我們要返回JsonResult怎麼辦呢,就直接加上特性[HttpPost]行了。
這也正是自定義JsonResult時跟之前.net framework時不同的地方
方法,自定義NewJsonResult繼承JsonResult 然後重寫ExecuteResult方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Http;
//using System.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;
namespace MyMis.MvcHelper {
public class NewJsonResult:JsonResult {
public NewJsonResult(object value)
:base(value){
}
public override void ExecuteResult(ActionContext context) {
if (context == null) {
throw new ArgumentException("序列化內容不能爲null");
}
if (context.HttpContext == null || context.HttpContext.Response == null) {
return;
}
context.HttpContext.Response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
//context.HttpContext.Response.ContentEncoding = ContentEncoding == null ? System.Text.Encoding.UTF8 : ContentEncoding;
if (Value != null) {
context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(Value));
}
}
}
}
將此方法加入自定義的ActionFilter中,自定義MyJsonActionFilter對OnActionExecuted進行自定義下調用上面的NewJsonResult來對JsonResult進行處理進行輸出
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MyMis.MvcHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyMis.Web.Filter
{
public class MyJsonActionFilter : Attribute, IActionFilter {
public void OnActionExecuted(ActionExecutedContext context) {
//Console.WriteLine("結束執行此操作");
if (context.Result is JsonResult && !(context.Result is NewJsonResult)) {
JsonResult jResult = (JsonResult)context.Result;
NewJsonResult result = new NewJsonResult(jResult.Value) { Value = jResult.Value, SerializerSettings= jResult.SerializerSettings, ContentType = jResult.ContentType };
context.Result = result;
}
}
public void OnActionExecuting(ActionExecutingContext context) {
Console.WriteLine("開始執行此操作");
}
}
}
最後我們要全局註冊下就直接在Startup文件中的ConfigureServices方法裏進行註冊下
services.AddMvc(m=> {
//註冊到集合的第一個
m.ModelBinderProviders.Insert(0, new ModelBinderProvider());
//註冊過濾器
m.Filters.Add(typeof(MyJsonActionFilter));
m.Filters.Add(typeof(CustomerExceptionFilter));
});
這樣,我們在Action中調用Json方法時就會用自定義的NewJsonResult方法來進行處理了