![]() |
|
Re-reading ASP.Net Core request bodies with EnableBuffering() - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: C#, Visual Basic & .NET (https://sickgaming.net/forum-79.html) +--- Thread: Re-reading ASP.Net Core request bodies with EnableBuffering() (/thread-89516.html) |
Re-reading ASP.Net Core request bodies with EnableBuffering() - xSicKxBot - 03-28-2019 Re-reading ASP.Net Core request bodies with EnableBuffering() Jeremy March 27th, 2019 <!–Posted on March 27, 2019 by Jeremy Meng–> In some scenarios there’s a need to read the request body multiple times. Some examples include
Usually Code: Request.BodyIn ASP.NET framework it was possible to read the body of an HTTP request multiple times using Code: HttpRequest.GetBufferedInputStreamIn ASP.NET Core 2.1 we added an extension method Code: EnableBuffering()Code: HttpRequestCode: InvokeAsync()Code: public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{ context.Request.EnableBuffering(); // Leave the body open so the next middleware can read it. using (var reader = new StreamReader( context.Request.Body, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: bufferSize, leaveOpen: true)) { var body = await reader.ReadToEndAsync(); // Do some processing with body… // Reset the request body stream position so the next middleware can read it context.Request.Body.Position = 0; } // Call the next delegate/middleware in the pipeline await next(context);
}The backing Code: FileBufferingReadStreamCode: EnableBuffering()Code: public static void EnableBuffering(this HttpRequest request, int bufferThreshold) public static void EnableBuffering(this HttpRequest request, long bufferLimit) public static void EnableBuffering(this HttpRequest request, int bufferThreshold, long bufferLimit)For example, a call of Code: context.Request.EnableBuffering(bufferThreshold: 1024 * 45, bufferLimit: 1024 * 100);enables a read buffer with limit of 100KB. Data is buffered in memory until the content exceeds 45KB, then it’s moved to a temporary file. By default there’s no limit on the buffer size but if there’s one specified and the content of request body exceeds the limit, an Code: System.IOExceptionThese overloads offer flexibility if there’s a need to fine-tune the buffering behaviors. Just keep in mind that:
Jeremy Meng Software Development Engineer Follow Jeremy https://devblogs.microsoft.com/aspnet/author/yumengmicrosoft-com/feed/ <!– –> |