默认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 }
View Code

相关文章:

  • 2022-12-23
  • 2021-09-24
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
猜你喜欢
  • 2021-10-10
  • 2022-01-16
  • 2022-12-23
  • 2021-10-06
  • 2021-08-21
  • 2022-12-23
  • 2021-12-30
相关资源
相似解决方案