ASP.NET MVC 中JsonResult返回的日期值为"/Date(1580709071513)/"问题
前言
经常在使用 JsonResult 返回日期都为 Date(1580709071513) 形式,多次处理形式都是在 js 中进行转换,每次都需要转换,因此,在此使用继承 JsonResult 并重写 ExecuteResult 方法处理日期格式。
代码示例
1. BaseController代码
public class BaseController : Controller { public const int success_code = 0; protected ActionResult FaultJson(string msg) { Res j = new Res() { status = "fail", msg = msg, }; return Json(j); //return Json(new { status = "fail", msg = msg }); } protected ActionResult SuccessJson(string msg) { Res j = new Res() { status = "success", msg = msg, }; return Json(j); //return Json(new { status = "success", msg = msg }); } protected ActionResult nxJson(string errmsg, int errcode, object data) { return new NxJsonResult(new { errcode = errcode, errmsg = errmsg, data = data }); } } public class Res { public string status { get; set; } public string msg { get; set; } } public class NxJsonResult : JsonResult { public NxJsonResult() { } public NxJsonResult(object Data) { this.Data = Data; } public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; response.ContentType = "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data != null) { Newtonsoft.Json.Converters.IsoDateTimeConverter timeFormat = new Newtonsoft.Json.Converters.IsoDateTimeConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data, Newtonsoft.Json.Formatting.Indented, timeFormat)); //Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(response.Output) { Formatting = Newtonsoft.Json.Formatting.Indented }; //Newtonsoft.Json.JsonSerializer serializer = Newtonsoft.Json.JsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings()); //serializer.Serialize(writer, Data); //writer.Flush(); } } }
2.调用
public ActionResult Test() { //return Json(new { date = DateTime.Now, str = "hello" }, JsonRequestBehavior.AllowGet); return new NxJsonResult(new { date = DateTime.Now, str = "hello" }); }
结果