【问题标题】:Is there a way to ensure the HTTP request body can be loaded into memory for possible multiple read requests?有没有办法确保可以将 HTTP 请求正文加载到内存中以进行可能的多个读取请求?
【发布时间】:2020-01-13 21:34:59
【问题描述】:

有没有办法确保 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】:

    对于 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

    【讨论】:

    • HttpContext.Request.EnableBuffering();也适用于 .Net Core 2.1。
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多