解决MVC 时间序列化的方法

1.全局处理 

处理代码

 1  publict static void SetSerializationJsonFormat(HttpConfiguration config)
 2         {
 3             // Web API configuration and services
 4             var json = config.Formatters.JsonFormatter;
 5             ////(时间格式只支持2种)json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
 6             ////时间格式("自定义格式")
 7             json.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
 8             ////移除json序列化器
 9             ////config.Formatters.Remove(config.Formatters.JsonFormatter);
10         }

在Application_Start调用SetSerializationJsonFormat(GlobalConfiguration.Configuration)全局设置

2.重写ActionResult

 1     public class JsonResult : ActionResult
 2     {
 3         public JsonResult()
 4         {
 5             this.ContentEncoding = Encoding.UTF8;
 6             this.ContentType = "application/json";
 7         }
 8 
 9         public override void ExecuteResult(ControllerContext context)
10         {
11             if (context == null)
12             {
13                 throw new ArgumentNullException("context");
14             }
15 
16             HttpResponseBase response = context.HttpContext.Response;
17             if (!string.IsNullOrEmpty(this.ContentType))
18             {
19                 response.ContentType = this.ContentType;
20             }
21             if (this.ContentEncoding != null)
22             {
23                 response.ContentEncoding = this.ContentEncoding;
24             }
25             if (this.Data != null)
26             {
27                 response.Write(NewtonsoftSerialize(this.Data));
28                 response.End();
29             }
30         }
31 
32         public Encoding ContentEncoding { get; set; }
33 
34         public string ContentType { get; set; }
35 
36         public object Data { get; set; }
37 
38         private static string NewtonsoftSerialize(object value)
39         {
40             try
41             {
42                 IsoDateTimeConverter timeFormat = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
43                 return JsonConvert.SerializeObject(value, timeFormat);
44             }
45             catch
46             {
47                 return string.Empty;
48             }
49         }
50     }
原文地址:https://www.cnblogs.com/liuxiaoji/p/4572069.html