简体   繁体   中英

C# .NET web api return from post request

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM