【问题标题】:ASP.NET MVC Json DateTime Serialization conversion to UTCASP.NET MVC Json DateTime 序列化转换为 UTC
【发布时间】:2013-02-20 06:02:30
【问题描述】:
在 ASP.NET MVC 控制器上使用 Json() 方法给我带来了麻烦 - 这个方法中抛出的每个 DateTime 都会使用服务器时间转换为 UTC。
现在,有没有一种简单的方法可以告诉 ASP.NET MVC Json Serializer 停止将 DateTime 自动转换为 UTC?正如this question 中指出的那样,使用 DateTime.SpecifyKind(date, DateTimeKind.Utc) 重新签名每个变量就可以了,但显然我不能对每个 DateTime 变量手动执行此操作。
那么是否可以在 Web.config 中设置某些内容并让 JSON 序列化程序将每个日期都视为 UTC?
【问题讨论】:
标签:
asp.net-mvc
json
asp.net-mvc-3
datetime
json.net
【解决方案1】:
该死,最近我似乎注定要在 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