Asp.netCore 3.1 WebApi时间类型的格式一直报错The JSON value could not be converted to System.DateTime. 解决方案
在用Asp.netCore 3.1 开发 WebApi 接口,若有时间类型的字段,会经常一个错误。
入参:
{ "schoolId": 111, "beginTime": "2020-08-18 08:00:00", "endTime": "2020-08-18 10:00:00", }
然后就会报错:
The JSON value could not be converted to System.DateTime. Path: $.beginTime | LineNumber: 0 | BytePositionInLine: 48.
{ "code": 400, "msg": "The JSON value could not be converted to System.DateTime. Path: $.beginTime | LineNumber: 0 | BytePositionInLine: 48." }
为啥会有这个错误?时间格式明明没问题啊。
原因为程序无法正常解析该json, 主要是为了提升执行效率;System.Text.Json作为微软内置json处理,效率更高更快。
那么这个微软官方的json会认识什么格式的时间值呢?它只认下面的格式
2020-08-18T08:00
年月日和时分秒之间加一个T就OK了。
当然,还有一个解决方案,若你执意不想要这个T,我们可以将微软默认的Json解析换掉,换成NewtonsoftJson就可以了。
为Controllers添加NewtonsoftJson注册,在Startup.cs下
public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); }
需要安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包。
作者:沐雪
文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
为之网-热爱软件编程 http://www.weizhi.cc/