【问题标题】:How to specify date format in RestSharp request如何在 RestSharp 请求中指定日期格式
【发布时间】:2021-05-31 18:36:27
【问题描述】:

我有这段代码:

            var client = new RestClient(fullUri);
            var request = new RestRequest(GetMethod(method));
            client.UseSerializer(
                () => new RestSharp.Serialization.Json.JsonSerializer { DateFormat = "yyyy-MM-dd HH:mm:ss" }
            );
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            if (body != null)
                request.AddJsonBody(body);
            var response = client.Execute(request);
            if (response.ErrorException != null)
                throw response.ErrorException;
            return JsonConvert.DeserializeObject<ResponseData>(response.Content);

注意

        client.UseSerializer(
            () => new RestSharp.Serialization.Json.JsonSerializer { DateFormat = "yyyy-MM-dd HH:mm:ss" }
        );

我添加了该代码,因为我需要将日期格式设置为 yyyy-MM-dd HH:mm:ss 而不是 yyyy-MM-ddTHH:mm:ss.zzzzz(默认)

RestRequest.DateFormat 已过时。

进行调用时,我看到使用默认格式而不是自定义格式传递日期。

我该怎么做?

【问题讨论】:

    标签: restsharp


    【解决方案1】:

    我会建议重写你的代码。这是我的 cmets 和示例:

    1. 首先,如果您尝试将这种格式用于 DateTime yyyy-MM-dd HH:mm:ss,当您尝试发送请求时,您将收到来自 Web API 服务的验证错误。
    {
       "type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
       "title":"One or more validation errors occurred.",
       "status":400,
       "traceId":"00-a0c978c054625441b8ddf4c552b0f34c-314723fc8ce3ac4e-00",
       "errors":{
          "$.DateTime":[
             "The JSON value could not be converted to System.DateTime. Path: $.DateTime | LineNumber: 0 | BytePositionInLine: 33."
          ]
       }
    }
    

    这意味着 - 您对 DateTime 使用了不正确的格式。您应该使用这种格式"yyyy-MM-ddTHH:mm:ss"。阅读更多有问题的The JSON value could not be converted to System.DateTime。 不要忘记添加T,因为解析器使用ISO_8601

    1. 其次,我强烈建议 不要使用 JsonSerializer from RestSharp,因为我遇到了不同的问题。我强烈建议使用来自 Microsoft 的 System.Text.JsonNewtonsoft.Json。阅读有关System.Text.JsonNewtonsoft.Json 的更多信息。

    2. 第三,让我们编码吧!我的 web api 服务示例。

            [HttpGet]
            public string Test()
            {
                var client = new RestClient("your url");
                var request = new RestRequest(Method.POST);
    
                var body = new SimpleRequestBody
                {
                    DateTime = DateTime.Now
                };
                var json = JsonConvert.SerializeObject(body,
                    new JsonSerializerSettings()
                    {
                        DateFormatString = "yyyy-MM-ddTHH:mm:ss"
                    });
    
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Accept", "application/json");
                if (body != null)
                    request.AddParameter("application/json", json, null, ParameterType.RequestBody);
    
                var response = client.Execute(request);
                // response.ErrorException -> Could not handle bad request
                // Better to user IsSuccessful property
                if (!response.IsSuccessful)
                    throw new Exception(response.Content);
    
                return response.Content;
            }
            public class SimpleRequestBody
            {
                public DateTime DateTime { get; set; }
            }
    

    客户端web api代码示例:

            [HttpPost]
            public ActionResult Post([FromBody] SimpleResponse response)
            {
                var result = $"OK result from another web api. DateTime {response.DateTime}";
                return Ok(result);
            }
            public class SimpleResponse
            {
                public DateTime DateTime { get; set; }
            }
        }
    
    1. 结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-14
      • 2022-12-16
      • 1970-01-01
      • 2016-03-08
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多