Search code examples
c#asp.net-corehttprequesthttpcontextsystem.net.httpwebrequest

Is there a way to ensure the HTTP request body can be loaded into memory for possible multiple read requests?


Is there a way to ensure the HTTP request body can be loaded into memory? There are multiple middle-wares which will use same HTTP Request body to log at multiple levels.

I remember doing following in .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);
}

Can anyone help me find similar behavior in .Net Core?

EDIT

-- I think right answer here is to use EnableBuffering, but I am not to able to figure out which overloaded method should I use for 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);
    }

Size of HTTP Request in our application is varying from 50kb to 300mb.


Solution

  • For asp.net core 2.x you can use :

    HttpContext.Request.EnableRewind();
    

    For asp.net core 3.x you can use :

    HttpContext.Request.EnableBuffering();
    

    That methods ensure the request Body can be read multiple times. Normally buffers request bodies in memory :

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