I was having an issue with my .NET Core API where when DateTimes were serializes, it would leave off milliseconds if the value was 0. This question explains the issue. I added the following to my .NET Core Startup class and it resolved the issue such that when I did a GET
, all dates would be formatted correctly:
services.AddMvc()
.AddJsonOptions(options =>
{
var settings = options.SerializerSettings;
var dateConverter = new IsoDateTimeConverter
{
DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff"
};
settings.Converters.Add(dateConverter);
});
After implementing this, I found that it broke default model bindings elsewhere. For example, I have a POST
endpoint that accepts the following viewmodel:
public class PatientRegistrationViewModel
{
public DateTime DateOfBirth { get; set; }
}
Previously I was passing the following JSON data in the request body which it bound successfully:
{
dateOfBirth: '1981-04-18'
}
After implementing the date converter above, the viewmodel equals null in my controller.