【发布时间】:2017-03-30 09:07:10
【问题描述】:
我将 ASP.NET 与 WebApi's(Rest) 和 AngularJS 一起使用。如果我将 DateTime 对象从客户端(Angular)发送到服务器(C#),我会因为时区而收到失真(-2 小时)的日期。所以我决定使用 Automapper。
我当前的代码如下所示:
AutoMapperConfiguration.cs:
public class AutoMapperConfiguration
{
public void Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DateTime, DateTime>().ConvertUsing<UtcToLocalConverter>();
});
}
}
UtcToLocalConverter.cs:
public class UtcToLocalConverter : AutoMapper.ITypeConverter<DateTime, DateTime>
{
public DateTime Convert(DateTime source, DateTime destination, ResolutionContext context)
{
var inputDate = source;
if (inputDate.Kind == DateTimeKind.Utc)
{
return inputDate.ToLocalTime();
}
return inputDate;
}
}
Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
new AutoMapperConfiguration().Configure();
//...some more stuff...
}
}
我希望自动转换从客户端收到的所有 DateTime 类型的对象,但这段代码不会发生这种情况。我做错了什么?有人可以帮我解决这个问题吗?
提前致谢。
【问题讨论】:
-
你在调试中看到
inputDate.Kind包含什么值了吗?我想是DateTimeKind.Unspecified -
您的应用程序是否从不同的位置使用?如果是,那么是否以当前用户当地时间显示时间?
-
我希望该函数会被自动调用。从包含 dateTime 对象的客户端获得任何响应后,它不会被调用。而且没有我的应用程序没有从不同的位置使用......
-
看看这个[链接][stackoverflow.com/questions/12937968/…,这会有所帮助。
标签: c# asp.net angularjs datetime automapper