DateTime loses precision when serialized and used as a url parameter using Refit

Viewed 977

I'm building an API Gateway that got an endpoint that takes DateTime value as a parameter. It forwards this query to an underlying microservice using Refit.

My problem is that when the URL for the query to the microservice is built, the DateTime values have lost precision.

Is there a way to configure Refit to use a custom DateTime serializer when building URLs?

The microservice endpoint is defined like this:

[Get("/client-sales")]
Task<ClientSaleCollectionR12n> SearchClientSales([Header("Authorization")] string authorization,
                                                         DateTime? completedAfter = null,
                                                         DateTime? completedBefore = null);

The query sent to the gateway:

GET /client-sales?completedAfter=2020-03-20T14:54:26.786&completedBefore=2020-03-21T15:16:33.212

Becomes this when forwarded to the underlying microservice:

GET /client-sales?completedAfter=03%2F20%2F2020%2014%3A54%3A26&completedBefore=03%2F21%2F2020%2015%3A16%3A33
2 Answers

I was able to specify the format when defining the Interface.

Task<ClientSaleCollectionR12n> SearchClientSales([Header("Authorization")] string authorization,
                                                         [Query(Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")] DateTime? completedAfter = null,
                                                         [Query(Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")] DateTime? completedBefore = null);

Since refit uses Newtonsoft.Json, maybe setting the DateTimeZoneHandling on the JsonConverter that refit uses works?

https://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm

I came across this since we had the same question, and didn't get a chance yet to try it. but this would be a more universal (/better) approach, if you don't have to specify the format everywhere.

Related