Using NodaTime Instant in a WebAPI Model Always Fails

One of my WebAPI v4 endpoint models has a field of type NodaTime.Instant . The model check always reports that this fails ( Model.IsValid == false ), with the error message "Unexpected parsing of the Instant token. Expected string, received date". which clearly comes from NodaTime .

The request message does transmit Instant as a string containing an ISO-8601 date, so it must be parsed in BCL DateTime at some point before NodaTime receives it. I tried using OffsetDateTime and LocalDateTime , but in each case I got similar errors.

So what should I do here? Should I convey something other than Instant ? Is there any other way to handle parsing or validation that does not lead to this error?

I have included minimum playback below. It must fail if you send it a message with the request body, for example {"SomeInstant":"2013-08-13T17:51:22.1705292Z"}

 using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Net; using System.Net.Http; using System.Web.Http; using NodaTime; namespace TestProject.Controllers { /** Assume that we called GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Bcl) in Global.asax.cs **/ public class NodaTimeController : ApiController { public Instant Post(TestModel m) { //ModelState.IsValid is always false due to error parsing the Instant field if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } return m.SomeInstant; } } public class TestModel { public Instant SomeInstant { get; set; } } } 
+4
source share
1 answer

Thanks to the joys of Twitter, it seems like it's just a matter of disabling the automatic handling of DateTime in Json.NET, for example.

 [...]JsonFormatter.SerializerSettings.DateParseHandling = DateParseHandling.None 

Perhaps we should fix the configuration method to do this automatically ...

Note that this will also disable the processing of "Date(...)" values, so you need to be careful with it. If you, of course, have full control of the caller, this should not be a problem.

+2
source

Source: https://habr.com/ru/post/1496887/


All Articles