有没有一种方法可以确保可以将HTTP请求正文加载到内存中以进行可能的多个读取请求?

问题描述 投票:0回答:1

是否有一种方法可以确保HTTP请求正文可以加载到内存中?有多种中间件,它们将使用相同的HTTP请求正文在多个级别上进行日志记录。

我记得在.Net Framework 4.6中执行以下操作

await request.Content.LoadIntoBufferAsync();


/// *** Method snapshot from HttpContent - System.Net.Http library ***
/// <summary>Serialize the HTTP content to a memory buffer as an asynchronous operation.</summary>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task LoadIntoBufferAsync()
{
  return this.LoadIntoBufferAsync((long) int.MaxValue);
}

任何人都可以帮助我在.Net Core中找到类似的行为吗?

编辑

-我认为正确的答案是使用EnableBuffering,但我无法弄清楚应该为EnableBuffering使用哪种重载方法?

    public static void EnableBuffering(this HttpRequest request)
    {
        BufferingHelper.EnableRewind(request);
    }

    public static void EnableBuffering(this HttpRequest request, int bufferThreshold)
    {
        BufferingHelper.EnableRewind(request, bufferThreshold);
    }

    public static void EnableBuffering(this HttpRequest request, long bufferLimit)
    {
        BufferingHelper.EnableRewind(request, bufferLimit: bufferLimit);
    }

我们应用程序中HTTP请求的大小从50kb到300mb不等。

asp.net-core httprequest httpcontext system.net.httpwebrequest
1个回答
1
投票

对于asp.net core 2.x,您可以使用:

HttpContext.Request.EnableRewind();

对于asp.net core 3.x,您可以使用:

HttpContext.Request.EnableBuffering();

该方法可确保可以多次读取请求正文。通常在内存中缓冲请求主体:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.httprequestrewindextensions.enablebuffering?view=aspnetcore-3.1

© www.soinside.com 2019 - 2024. All rights reserved.