将 HttpContext 请求内容数据复制到新请求 [英] Copy HttpContext request content data to new request
问题描述
我正在为我们的 dotnet 核心微服务平台构建 APIGateway 代理.
I am building a APIGateway proxy for our dotnet core microservices platform.
我使用了 https://medium.com/@mirceaoprea/api-gateway-aspnet-core-a46ef259dc54 作为起始位置,它使用
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
});
您拥有向网关发出请求的上下文,但如何将网关请求中的内容数据复制到我要向 API 发出的新请求中?
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?
我看到了将请求内容设置为 HttpContent 对象的能力:
I see the ability to set the request content to a HttpContent object:
newRequest.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
但我希望我的应用程序通过网关进行文件上传,我发现这样做的唯一方法是创建 MultipartFormDataContent,但所有关于如何创建 MultipartFormDataContent 的示例都使用 IFormFile 而不是 HttpContext.
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.
是否可以将初始 apigateway 请求中的内容复制到我的内部请求中:
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
}
}
推荐答案
您可以使用 StreamContent
为此,传入 HttpContext.Request.Body
Stream
作为要使用的实际内容.这是您的示例中的样子:
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);
顺便说一句,请确保您使用 HttpClient 的共享实例.
As an aside, make sure that you use a shared instance of HttpClient.
这篇关于将 HttpContext 请求内容数据复制到新请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!