首页 > 解决方案 > 如何在 RestSharp 请求中指定日期格式

问题描述

我有这段代码:

            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. 首先,如果您尝试对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"。阅读更多有问题的 JSON 值无法转换为 System.DateTime。不要忘记 addT因为解析器使用ISO_8601

  1. 其次,我强烈建议不要使用 JsonSerializerfrom RestSharp,因为我遇到了不同的问题。我强烈建议使用System.Text.JsonMicrosoft 或Newtonsoft.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. 结果

json值

API 响应


推荐阅读