随笔 - 22, 文章 - 0, 评论 - 97, 阅读 - 58658
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

关于ASP.NET MVC 中JsonResult返回的日期值问题

Posted on   冲杀  阅读(3258)  评论(0编辑  收藏  举报

最近开始用MVC做项目,在使用 JsonResult返回数据的时候,日期被反射成了/Date 1233455这种格式,遍查网上都是在客户端使用JS来处理这个问题的,这样的话,就需要在每一个涉及到日期的地方都做一次转换后,才能用来使用。

  于是我通过反编译Controller抽象类以及JsonResult类后发现:

  jsonresult中处理对象到JSON字符串的方法:

复制代码
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
        }
        HttpResponseBase response = context.HttpContext.Response;
        if (!string.IsNullOrEmpty(this.ContentType))
        {
            response.ContentType = this.ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }
        if (this.Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            response.Write(serializer.Serialize(this.Data));
        }
    }
复制代码

在这个方法里使用的是JavaScriptSerializer这个来序列化对象到JSON。

于是我自定义了一个类,继承JSONRESULT类

并将上面的方法从写 ,用newton.json替换javascriptSerializer

替换代码如下:

if (this.Data != null)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
        timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            response.Write(JsonConvert.SerializeObject(this.Data, Newtonsoft.Json.Formatting.Indented, timeFormat, x););
        }

这样处理了日期的JSON序列化。

然后再重新定义一个Controller,命名为 JsonController,且设置为抽象类。

然后重写方法:

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
}

将 JsonResult改为我们继承JSONResult并重写了ExecuteResult方法的类,就大工告成了!

 以后只要JsonResult涉及到返回日期的,就可以让控制器继承我们自定义的这个类,由此解决日期问题。

 

以上只解决了日期JSON后在JS中使用显示的问题,未解决日期参与运算的问题,但是根据我目前的经历,JS中日期参与预算的时间还比较少,所以能解决用于显示的问题,就很OK了,

ASP.NET MVC还有很多好玩的特性,大家一起摸索吧!

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示