RestSharp将Datetimes转换为UTC

its*_*end 6 c# restsharp

我有以下问题

我正在使用RestSharp来访问我的API.但是当我发送DateTime时,它似乎转换为UTC.我发送'10 .06.1991 00:00',API得到'09 .06.1991 22:00'

那么,当我的API获取DateTime对象时,我总是需要增加2个小时?

我检查了JSON RestSharp发送给API.

public class Test
{
    public int IntProperty {get;set;}
    public string StringProperty {get;set;}
    public DateTime DateTimeProperty {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我的目标是

Test t = new Test{ IntProperty=3, StringProperty="string", DateTimeProperty=new DateTime(1991,06,10) }
Run Code Online (Sandbox Code Playgroud)

当我通过RestSharp发送对象时,我的API接收的JSON是

{
    "IntProperty":3,
    "StringProperty":"string",
    "DateTimeProperty":"09.06.1991 22:00:00"
}
Run Code Online (Sandbox Code Playgroud)

知道我能做什么吗?谢谢

Mat*_*ger 7

接收错误数据的不是您的API,而是发送错误数据的是您的客户端。我的API遇到了同样的问题。不,它是正确的数据,但已转换为UTC。

确切的问题在这里描述:https//github.com/restsharp/RestSharp/issues/834

因此,不要在您通过API获得的每个DateTime中添加2小时。当另一个客户端发送未转换的日期时,您可能会更改正确的数据。

  1. 您可以检查是否在GET上收到正确的日期。也许RestSharp正在将“错误的”日期时间转换回10.06.1991 00:00-也许您还可以
  2. 如果您希望数据库不包含UTC而是原始要发送的数据,请不要使用默认的序列化程序,请使用JSON.Net(http://www.newtonsoft.com/json)。它不会转换为UTC并发送原始的DateTime。

这是一个有关如何实现的非常好的示例:http : //bytefish.de/blog/restsharp_custom_json_serializer/

  • 您编写了一个实现ISerializerIDeserializer
  • 在序列化中,您调用JSON.Net;Serialize在反序列化中,您调用JSON.NetDeserialize

  • 您只需要像这样向您的RestClient添加一个处理程序:(我使用的是上述博客中描述的静态Default-instance)

我的客户看起来像:

private readonly RestClient _client;

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

在请求中,您可以设置JsonSerializer

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