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

    }
Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
  • Hello! Did you find an answer for this any chance? If you did, could you help me out and post it please? Thanks! – PKCS12 Jul 27 '18 at 14:42
  • 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. – Larry Lustig Jul 27 '18 at 16:14
  • @LarryLustig did you find the answer? – LP13 Jan 10 '19 at 19:32
  • 1
    Does this answer your question? [Convert from HttpResponseMessage to IActionResult in .NET Core](https://stackoverflow.com/questions/51641641/convert-from-httpresponsemessage-to-iactionresult-in-net-core) – Martin Nov 21 '20 at 17:31

1 Answers1

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);
}
willwolfram18
  • 1,747
  • 13
  • 25