Convert HttpResponseMessage to ActionResult in Dot Net Core proxy controller action
Asked Answered
P

1

11

The following method is intended to accept an Http method and url, execute the method against the url, and return the resulting response to the caller. It returns ActionResult because there are error conditions that need to be handled.

At present, the method only tells the caller whether the call succeeded or not, it doesn't return details about the response from the downstream server. I would like the caller to receive the entire response (including status code, response body, etc) from the call.

How can I convert the HttpResponseMessage to something appropriate to return via ActionResult?

    [HttpGet(@"{method}")]
    public async Task<IActionResult> RelayRequest(string method, [FromQuery] string url)
    {

        var httpMethod = new HttpMethod(method);

        Uri uri;
        try
        {
            uri = new Uri(url);
        }
        catch (Exception e)
        {
            return BadRequest("Bad URL supplied: " + e.Message);
        }

        var request = new HttpRequestMessage(httpMethod, uri);

        try
        {
            var response = await _httpClient.SendAsync(request);
            // WANT TO RETURN (ActionResult)response HERE! <<<<<<<<<<

            if (response.IsSuccessStatusCode)
            {
                return Ok();
            }
            return BadRequest(response);
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }

    }
Plectrum answered 23/4, 2018 at 13:53 Comment(4)
Hello! Did you find an answer for this any chance? If you did, could you help me out and post it please? Thanks!Dungdungan
Sadly, no solution yet. When I am on-site with this customer I will try to refer to the source code and see what I did for a work-around.Plectrum
@LarryLustig did you find the answer?Solfatara
Does this answer your question? Convert from HttpResponseMessage to IActionResult in .NET CoreApostil
P
0

It's going to depend a little bit on the response you're receiving from your await _httpClient.SendAsync(request) but you could deserialize the response Content from the request and return that from your controller.

For example, if the request used JSON, you could do the following:

if (response.IsSuccessStatusCode)
{
    // Assuming the use of Newtonsoft.Json
    var responseBody = JsonConvert.DeserializeObject<RequestResponse>(await response.Content.ReadyAsStringAsync());

    return Ok(responseBody);
}
Petulah answered 24/6, 2019 at 3:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.