0

I have this piece of code:

            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);

Note the

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

I have added that code because I need the date format to be yyyy-MM-dd HH:mm:ss instead of yyyy-MM-ddTHH:mm:ss.zzzzz (the default)

RestRequest.DateFormat is obsolete.

When the calling is made, I saw that a date is passed using the default format, instead of the custom one.

How can I do it?

jstuardo
  • 3,901
  • 14
  • 61
  • 136

1 Answers1

3

I will suggest rewrite your code. Here my comments and example:

  1. First, if you try to use this format for DateTime yyyy-MM-dd HH:mm:ss you will get a validation error from web API service when you try to send a request.
{
   "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."
      ]
   }
}

This means - you use incorrect format for DateTime. You should use this format "yyyy-MM-ddTHH:mm:ss". Read more in question The JSON value could not be converted to System.DateTime. Don't forget add T because parsers use ISO_8601

  1. Second, I would highly recommend do not use JsonSerializer from RestSharp, because I faced different problems with it. I highly recommend to use System.Text.Json from Microsoft or Newtonsoft.Json. Read more about System.Text.Json or Newtonsoft.Json.

  2. Third, let's code! My example of web api service.

        [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; }
        }

Example of client web api code:

        [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. Results

Json value

Api response

DarkSideMoon
  • 835
  • 1
  • 11
  • 17