加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC Json DateTime序列化转换为UTC

发布时间:2020-12-16 00:05:02 所属栏目:asp.Net 来源:网络整理
导读:在ASP.NET MVC Controller上使用Json()方法给我带来了麻烦 – 此方法中抛出的每个DateTime都使用服务器时间转换为UTC. 现在,有没有一种简单的方法告诉ASP.NET MVC Json Serializer停止自动将DateTime转换为UTC?正如在this question中指出的那样,使用DateTim
在ASP.NET MVC Controller上使用Json()方法给我带来了麻烦 – 此方法中抛出的每个DateTime都使用服务器时间转换为UTC.

现在,有没有一种简单的方法告诉ASP.NET MVC Json Serializer停止自动将DateTime转换为UTC?正如在this question中指出的那样,使用DateTime.SpecifyKind(date,DateTimeKind.Utc)重新分配每个变量可以解决问题,但显然我无法在每个DateTime变量上手动执行此操作.

那么可以在Web.config中设置一些内容并让JSON序列化程序将每个日期视为UTC吗?

解决方法

该死,似乎最近我注定要在StackOverflow回答我自己的问题.叹了口气,这是解决方案:

>使用NuGet安装ServiceStack.Text – 您将免费获得更快的JSON序列化(欢迎您)
>一旦安装了ServiceStack.Text,只需覆盖基础控制器中的Json方法(你有一个,对吧?):

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

public class ServiceStackJsonResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }

        if (Data != null)
        {
            response.Write(JsonSerializer.SerializeToString(Data));
        }
    }
}

>看起来这个序列化程序默认情况下是“正确的” – 如果DateTime.Kind未指定,它不会弄乱你的DateTime对象.但是,我在Global.asax中做了一些额外的配置调整(在开始使用库之前知道如何做到这一点很好):

protected void Application_Start()
{
    JsConfig.DateHandler = JsonDateHandler.ISO8601;
    JsConfig.TreatEnumAsInteger = true;

    // rest of the method...
}

This link helped

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读