项目场景:
项目使用.NetCore 3.1框架,WebAPI 定义一个 Post 一个接口。
参数:Model实体类(包含 DateTime类型 字段),代码如下。
[Route("api/[controller]")]
[ApiController]
public class DateTimeTController : ControllerBase
{
/// <summary>
/// Post 接口,参数为DateTime类型
/// </summary>
/// <param name="value"></param>
[HttpPost]
public bool Post([FromBody] UserModel value)
{
if (value.ID < 0)
{
return false;
}
// ...业务处理
return true;
}
}
public class UserModel
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
}
问题描述:
【问题描述】:调试接口,向接口传以下参数,返回400 “The JSON value could not be converted to System.DateTime”
。
{
"id": 0,
"name": "TestName",
"createTime": "2020-01-01 06:53:10"
}
原因分析:
【分析】:json无法正常解析 DateTime 格式。可是 “2020-01-01 06:53:10”
格式明明是正确的,为什么无法解析呢?
原来是微软为了提高执行效率,将 System.Text.Json 作为内置 json 处理,但只识别 "2020-01-01T06:53:10"
这种格式 的时间值。
解决方案:
两种解决方案:
a. 时间类型传参格式 :日期与时间中间添加 T 字符,举例:“2020-01-01T06:53:10”。
b. 修改程序配置(微软不推荐)
在 startup.cs
配置文件中修改配置。提示:需要安装Microsoft.AspNetCore.Mvc.NewtonsoftJson。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
}