将HttpContext请求内容数据复制到新请求

时间:2018-09-25 20:44:14

标签: c# asp.net-core .net-core asp.net-core-2.0

我正在为我们的dotnet核心微服务平台构建APIGateway代理。

我以https://medium.com/@mirceaoprea/api-gateway-aspnet-core-a46ef259dc54作为起点,这会使用来拾取所有请求

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

您具有到网关的请求的上下文,但是如何将内容数据从网关请求复制到要对我的API提出的新请求?

我看到了将请求内容设置为HttpContent对象的功能:

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

但是我希望我的应用程序通过网关进行文件上传,我发现这样做的唯一方法是创建MultipartFormDataContent,但是有关如何创建MultipartFormDataContent的所有示例都使用IFormFile而不是HttpContext。

是否可以将初始apigateway请求中的内容复制到我的内部请求中?

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

1 个答案:

答案 0 :(得分:1)

您可以为此使用StreamContent,并将HttpContext.Request.Body Stream作为要使用的实际内容。这就是您的示例中的样子:

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

顺便说一句,请确保使用shared instance of HttpClient