Cale
Cale

Reputation: 617

Copy HttpContext request content data to new request

I am building a APIGateway proxy for our dotnet core microservices platform.

I used https://medium.com/@mirceaoprea/api-gateway-aspnet-core-a46ef259dc54 as a starting place, this picks up all requests by using

app.Run(async (context) =>
{
   // Do things with context
});

You have the context for the request to the gateway, but how do I copy over the content data from the gateway request to a new request I am going to make to my API?

I see the ability to set the request content to a HttpContent object:

newRequest.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");

But I want my application to take file uploads through the gateway, the only way I found to do it is to create a MultipartFormDataContent, but all examples on how to create a MultipartFormDataContent use a IFormFile instead of a HttpContext.

Is there a way to just copy the content on the initial apigateway request to my internal request:

using (var newRequest = new HttpRequestMessage(new HttpMethod(request.Method), serviceUrl))
{
    // Add headers, etc

    newRequest.Content = // TODO: how to get content from HttpContext

    using (var serviceResponse = await new HttpClient().SendAsync(newRequest))
    {
        // handle response
    }
}

Upvotes: 2

Views: 6540

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93233

You can use StreamContent for this, passing in the HttpContext.Request.Body Stream as the actual content to use. Here's what that looks like in your example:

newRequest.Content = new StreamContent(context.Request.Body);

As an aside, make sure that you use a shared instance of HttpClient.

Upvotes: 4

Related Questions