在Web API中绑定DateTimes时遇到了一些麻烦。这是情况。我有一个控制器,该控制器返回带有DateTime属性的模型。我已经将Web api设置为在global.asax中使用IsoDateFormat和UTC时间,如下所示:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
Run Code Online (Sandbox Code Playgroud)
日期时间格式以以下格式返回给客户端:2013-02-04T11:24:48.91Z
在这方面,一切都很好。但是,如果我以相同的格式将其发布回来,则模型联编程序将无法识别该属性并将其保留为空。为了使默认的DateTime模型绑定起作用,输入日期时间需要采用哪种格式?
我已按照您指定的方式配置了我的 Web API 服务,并且我能够发布您指定格式的日期时间。您有[FromBody]DateTime 参数吗?默认情况下是原始类型[FromUri]。
public DateTime Post([FromBody]DateTime date)
{
return date;
}
Run Code Online (Sandbox Code Playgroud)
要求:
POST http://localhost/api/values HTTP/1.1
content-type: application/json
Content-Length: 25
"2013-02-04T11:24:48.91Z"
Run Code Online (Sandbox Code Playgroud)
回复:
HTTP/1.1 200 OK
Content-Length: 25
Content-Type: application/json; charset=utf-8
"2013-02-04T11:24:48.91Z"
Run Code Online (Sandbox Code Playgroud)