How to forward HTTP response to client

asp.net-core, asp.net-core-webapi, c#

Solution

Look at aspnet/AspLabs repository for a good example of a transparent HTTP proxy. This proxy is a middleware handling client's requests to A and making its own requests to B.

To provide a complete answer, this is the part of its source code which is actually forwarding a `HttpResponseMessage`:

using (var responseMessage = await _httpClient.SendAsync(
    requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
    context.Response.StatusCode = (int)responseMessage.StatusCode;
    foreach (var header in responseMessage.Headers)
    {
        context.Response.Headers[header.Key] = header.Value.ToArray();
    }

    foreach (var header in responseMessage.Content.Headers)
    {
        context.Response.Headers[header.Key] = header.Value.ToArray();
    }

    // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
    context.Response.Headers.Remove("transfer-encoding");
    await responseMessage.Content.CopyToAsync(context.Response.Body);
}

There is full code copying a received `HttpResponseMessage` to the `HttpContext.Response` in the repository.

Problem

I have a client (Xamarin) and two Web API servers, A and B. The client makes a request to A which uses the request parameters to make another request to B. How do I return the response that A receives from B to the client such that B's use of C is transparent to the client. For example, if I make a request from A to B using `HttpClient` how do I forward the `HttpResponseMessage` to the client in a controller's action?

Original source