RestSharp converts Datetimes to UTC

It's not your API that receives wrong data, it's your client that sends "wrong" data. I got the same problem with my API. No, it's correct data but converted to UTC.

The exact problem is described here: https://github.com/restsharp/RestSharp/issues/834

So, don't add 2 hours to each DateTime you get it in your API. You would perhaps change correct data when another client sends unconverted dates.

  1. You could check, whether on GET you receive the right date. Maybe RestSharp is converting that "wrong" datetime back to 10.06.1991 00:00 - maybe you are okay with it
  2. if you want the database to not contain UTC but the data you original wanted to send, don't use the default serializer, use JSON.Net (http://www.newtonsoft.com/json). It won't convert to UTC and sends the original DateTime.

Here is one really good example on how to implement: http://bytefish.de/blog/restsharp_custom_json_serializer/

  • you write a custom class that implements ISerializer and IDeserializer
  • in serialize you call JSON.Net Serialize while in deserialize you call JSON.Net Deserialize

  • you just need to add a handler to your RestClient like this: (I'm using the static Default-instance described in the mentioned blog)

my client looks like:

private readonly RestClient _client;

public RestApiClient(string apiAdress)
{
    _client = new RestClient(apiAdress);
    _client.AddHandler("application/json", () => NewtonsoftJsonSerializer.Default);
}

and in requests you can set the JsonSerializer:

 IRestRequest restRequest = 
        new RestRequest(request.GetRestfulUrl(), request.Method) {
            RequestFormat = request.DataFormat, 
            JsonSerializer = NewtonsoftJsonSerializer.Default 
        };

Tags:

C#

Restsharp