Customized Webapi Response

Asked

Viewed 129 times

0

Hello, I have a Webapi service and would like to get an answer specifically with a Date, but at the time I call this service and get the return of my Postasync what I see is just an httpResult saying it was OK.

call to the Webapi var result = await client.Postasync(URI, content);

Return of the method in the web api Return Request.Createresponse(Httpstatuscode.OK, dateThis);

Whatever I send in return, I don’t get ...

I tried to change the return type of the method to Datetime, or string but it didn’t work either. Currently he is an Httpresponsemessage m

1 answer

0


See if this is something you need:

 [HttpPost]
 public IHttpActionResult Post([FromBody]DateTime newDate)
 {
      return Ok<DateTime>(newDate);
 }

The method OK<T>() is within the class ApiController used as the basis of your Webapi and is already responsible for serializing the parameter.

To read the content in C# you must follow this way:

using (var http = new HttpClient())
{               
    var requestBody = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = url,
        Content = new StringContent(body)
    };
    requestBody.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json") { CharSet = "UTF-8" };

    var httpResult = http.SendAsync(requestBody).GetAwaiter().GetResult();
    var resultContent = httpResult.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    var resultStatus = (httpResult.StatusCode == HttpStatusCode.OK);
    DateTime? myDate;
    if (resultStatus)
        myDate= JsonConvert.DeserializeObject<DateTime>(resultContent, JSettings);
    else
        myDate= null;
}

Abs.

  • But within the result of my call to the API I still didn’t find the date. Would the date be serialized in the Header property? How could I get the return? var result = await client.Postasync(URI, content);

  • I complemented my answer with the method of reading the return in C#. See if it suits you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.