1

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.

Community
  • 1
  • 1
mellis481
  • 4,332
  • 12
  • 71
  • 118

1 Answers1

1

One quick solution is to introduce and use WriteOnlyIsoDateTimeConverter:

public class WriteOnlyIsoDateTimeConverter : IsoDateTimeConverter
{
    public override bool CanRead { get { return false; } }
}

By overriding CanRead to return false, the model binder should continue to use the currently built-in date parsing while using the converter for output formatting.

Another option might be to replace the JsonOutputFormatter as shown in this question.

dbc
  • 104,963
  • 20
  • 228
  • 340