C# .NET web api return from post request

21,610

Solution 1

You need to read the content from response.

var contentString = response.Result.Content.ReadAsStringAsync().Result;

If you wish, you can then deserialize the string response into the object you want returning.

public async Task<TResult> TestGetAll<TResult>(string apiRoute, string json)
{
    // For simplicity I've left out the using, but assume it in your code.

    var response = await client.PostAsJsonAsync(url, json);

    var resultString = await response.Content.ReadAsStringAsync();

    var result = JsonConvert.DeserializeObject<TResult>(resultString);

    return result;
}

Solution 2

You have to return the response as an HttpResponseMessage.

Try changing your return statement to

[HttpPost("api/v1/testGetAll")]
public IHttpActionResult Test([FromBody]object filteringOptions)
{
    return Ok(myService.GetLogs(filteringOptions).ToArray());
}

Please note: This will return the response with status code 200. In case you want to handle the response based on different response code. You can create the HttpResponseMessage like this-

Request.CreateResponse<T>(HttpStatusCode.OK, someObject); //success, code- 200
Request.CreateResponse<T>(HttpStatusCode.NotFound, someObject); //error, code- 404

T is your object type.

And so on...

Share:
21,610
Norgul
Author by

Norgul

I'm cool

Updated on July 17, 2022

Comments

  • Norgul
    Norgul almost 2 years

    I am making a POST request to a route which is returning JSON data.

        [HttpPost("api/v1/testGetAll")]
        public object Test([FromBody]object filteringOptions)
        {
            return myService.GetLogs(filteringOptions).ToArray();
        }
    

    Route works fine, filtering works fine, and when I test the route in Postman I get the right response. However this is only a back-end, and I would like to invoke this route from my custom API gateway.

    The issue I'm facing is getting that exact response back. Instead I am getting success status, headers, version, request message etc.

        public object TestGetAll(string ApiRoute, T json)
        {
            Task<HttpResponseMessage> response;
            var url = ApiHome + ApiRoute;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    response = client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, "application/json"));
    
                    return response.Result;
                }
                catch (Exception e)
                {
                    ...
                }
            }
        }
    

    How can I get exact content back?

  • Norgul
    Norgul almost 7 years
    You mean IActionResult ? If so, it returns the same
  • Souvik Ghosh
    Souvik Ghosh almost 7 years
    Did you deserialize the response back to Array? Also show the content that you are getting in Postman.
  • Mark
    Mark about 5 years
    I know this Is old but the light gray stating the using is left out makes it harder for some of us. I upvoted though because it helped :) .. alot