当datetime通过json传递时,API对象为null

时间:2019-05-08 07:06:48

标签: c# api asp.net-core .net-core

我当前正在尝试创建POST请求以创建订单。 如果我这样放置json,效果很好:

  "Id": "A2EC1753-88DC-45E1-AD26-F887E0013323",
  "OrderType": "10",
  "Customer": "8111345C-95E3-460F-90FB-26E62E4265C4",
  "CustomerCode": "155542",
  "SubTotal": 417,
  "VatTotal": 0,
  "Total": 417,
 "Created": "2015-03-03T14:01:19.773+01:00",
  "Date": "2015-03-03T14:01:19.773+01:00",
.....

但是,当我给出客户发送的日期时(yyyy-mm-dd hh:mm:ss) 即:

"Id": "A2EC1753-88DC-45E1-AD26-F887E0013323",
  "OrderType": "10",
  "Customer": "8111345C-95E3-460F-90FB-26E62E4265C4",
  "CustomerCode": "155542",
  "SubTotal": 417,
  "VatTotal": 0,
  "Total": 417,
 "Created": "2019-04-26 16:53:39",
  "Date": "2019-04-26 16:53:39",
.....

控制器中的对象返回null。

Created和Date均为DateTime类型。

我在这里想念什么?

编辑:

因此,客户端将DateTime发送为yyyy-MM-dd HH:mm:ss。 显然,这不是.Net的默认json结构。

  

该规范包含对象,数组,字符串,整数和浮点数,但它没有定义日期的标准。 Json.NET使用的默认格式是ISO 8601标准:“ 2012-03-19T07:22Z”。在Json.NET 4.5之前,日期使用Microsoft格式编写:“ / Date(1198908717056)/”。15 feb。 2009

我尝试相应地更改它https://stackoverflow.com/a/49978720/7639883和下面的答案。

public void ConfigureServices(IServiceCollection services)
        {
            services.AddOData();
            services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // month must be capital. otherwise it gives minutes.
            }); 

            Setting.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<IsahContext>(
                options => options.UseSqlServer(Setting.ConnectionString)
            );
        }

但是由于某种原因,它仍然无法正常工作。

1 个答案:

答案 0 :(得分:1)

对于使用NewtonSoft.Json的Core版本(即3.0之前的版本),本文可能会有用:https://vikutech.blogspot.com/2017/01/handling-json-datetime-format-on-asp.net-core.html

如文章中所述,要使Newtonsoft.Json.Converters.IsoDateTimeConverter类处理的Json转换使用自定义日期格式,应在Configure方法中添加以下代码:

   services.AddMvc()  
   .AddJsonOptions(options =>  
   {  
     options.SerializerSettings.DateTimeZoneHandling = "MM/dd/yyyy HH:mm:ss";  
   });