Reputation: 857
I am currently trying to create a POST request to create an order. This works fine if I put my json like this:
"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",
.....
But when I give the date like my client is sending (yyyy-mm-dd hh:mm:ss) i.e.:
"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",
.....
The object in my controller returns null.
Created and Date are both of type DateTime.
What am I missing here?
Edit:
So, the client is sending the DateTime as yyyy-MM-dd HH:mm:ss. This is apparently not the default json structure for .Net.
The spec has objects, arrays, strings, integers, and floats, but it defines no standard for what a date looks like. The default format used by Json.NET is the ISO 8601 standard: "2012-03-19T07:22Z". Prior to Json.NET 4.5 dates were written using the Microsoft format: "/Date(1198908717056)/".15 feb. 2009
I've tried to change it accordingly https://stackoverflow.com/a/49978720/7639883 and the answer below.
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)
);
}
But for some reason it's still not functioning.
Upvotes: 2
Views: 988
Reputation: 86
For Core versions using NewtonSoft.Json (ie. pre-3.0), this article could be useful: https://vikutech.blogspot.com/2017/01/handling-json-datetime-format-on-asp.net-core.html
As described in the article, to direct the Json conversion handled by Newtonsoft.Json.Converters.IsoDateTimeConverter
class to use custom date formatting, the code below should be added in Configure method:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.DateTimeZoneHandling = "MM/dd/yyyy HH:mm:ss";
});
Upvotes: 1