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

Copy HttpContext request content data to new request

我正在为我们的 dotnet 核心微服务平台构建一个API网关代理。

我使用 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
    }
}

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

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

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