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

asp.net-web-api – asp web api DateTime模型绑定

发布时间:2020-12-16 09:52:49 所属栏目:asp.Net 来源:网络整理
导读:我在web api中绑定DateTimes时遇到了一些麻烦.情况就是这样.我有一个控制器,它返回一个带有DateTime属性的模型.我已经设置了我的web api,在global.asax中使用IsoDateFormat和UTC时间,如下所示: HttpConfiguration config = GlobalConfiguration.Configurati
我在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;

datetime格式以这种格式返回给客户端:
2013-02-04T11:24:48.91Z

这方面的一切都很好.但是,如果我以相同的格式发回它,模型绑定器不会识别该属性并将其保留为null.输入日期时间需要什么格式才能使默认的DateTime模型绑定起作用?

解决方法

我已经按照您指定的方式配置了我的Web API服务,并且我能够发布您指定格式的DateTime.你有DateTime参数的[FromBody]吗?原始类型默认为[FromUri].

public DateTime Post([FromBody]DateTime date)
{
    return date;
}

请求:

POST http://localhost/api/values HTTP/1.1
content-type: application/json
Content-Length: 25

"2013-02-04T11:24:48.91Z"

响应:

HTTP/1.1 200 OK
Content-Length: 25
Content-Type: application/json; charset=utf-8

"2013-02-04T11:24:48.91Z"

(编辑:李大同)

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

    推荐文章
      热点阅读