默认mvc json序列化 机制处理日期等字段时 格式并不是我们想要的格式
我们可以使用json.net 覆盖mvc默认的序列化行为
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Web; 8 using System.Web.Mvc; 9 using Newtonsoft.Json; 10 11 namespace Ecomm.Common.Web.Result 12 { 13 /// <summary> 14 /// 覆盖默认 JsonResult 中JavascriptSerializer 序列化json 改用 json.net 序列化对象。处理日期问题 15 /// </summary> 16 public class JsonNetResult : JsonResult 17 { 18 public JsonNetResult() 19 { 20 Settings = new JsonSerializerSettings 21 { 22 ReferenceLoopHandling = ReferenceLoopHandling.Error 23 }; 24 } 25 26 public JsonSerializerSettings Settings { get; private set; } 27 28 public override void ExecuteResult(ControllerContext context) 29 { 30 if (context == null) 31 throw new ArgumentNullException("context"); 32 if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) 33 throw new InvalidOperationException("JSON GET is not allowed"); 34 35 HttpResponseBase response = context.HttpContext.Response; 36 response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; 37 38 if (this.ContentEncoding != null) 39 response.ContentEncoding = this.ContentEncoding; 40 if (this.Data == null) 41 return; 42 43 var scriptSerializer = JsonSerializer.Create(this.Settings); 44 45 using (var sw = new StringWriter()) 46 { 47 scriptSerializer.Serialize(sw, this.Data); 48 response.Write(sw.ToString()); 49 } 50 } 51 } 52 }