5.9 — Reading and Rewinding the Request Body¶
← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.8 HttpContext · Next: 5.10 Built-in middleware
Markers: ⚠️ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Request.Body is a forward-only stream. Reading it consumes it — so if your middleware
reads the body, the model binder finds nothing and your action gets a null model.
EnableBuffering()makes the stream re-readable by keeping a copy.- After reading you must rewind it with
Body.Position = 0, or the next reader still sees nothing. - Buffering costs memory or disk. Do not do it for every request unless you have measured the cost.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
Request.Body |
a Stream property |
The raw bytes of the request body. Forward-only by default. |
| Forward-only stream | a stream property | Can be read once, start to finish. No seeking, no rewinding. |
EnableBuffering() |
an extension method | Swaps in a stream that remembers what it read, making it seekable. |
FileBufferingReadStream |
a class | What EnableBuffering installs. Buffers in memory, spilling to disk past a threshold. |
| Rewind | an action | Setting Body.Position = 0 so the next reader starts at the beginning. |
bufferThreshold |
a parameter | Bytes kept in memory before spilling to a temp file. Default 30 KB. |
bufferLimit |
a parameter | Maximum total size. Exceeding it throws. |
leaveOpen |
a StreamReader parameter |
Whether disposing the reader also disposes the stream. Must be true here. |
| Model binding | a framework step | Reads the body to construct your action's parameters. See 11.2. |
MaxRequestBodySize |
a Kestrel limit | The hard ceiling on body size. Default 30 MB. |
The concept¶
Why the body can only be read once¶
The request body arrives over a network socket. ASP.NET Core exposes it as a Stream that
reads directly from that socket as data arrives — nothing is stored.
That is a deliberate design for efficiency. A 2 GB file upload does not sit in memory; it flows through as it arrives.
The consequence: once bytes are read, they are gone. There is no buffer to re-read from.
A picture: water from a tap. You can fill a glass as it flows. What you did not catch has gone down the drain — you cannot ask the tap to send the same water again.
The bug this causes¶
// Logging middleware reads the body
app.Use(async (context, next) =>
{
using var reader = new StreamReader(context.Request.Body);
var body = await reader.ReadToEndAsync();
logger.LogInformation("Body: {Body}", body); // works — logs correctly
await next();
});
// The action gets nothing
[HttpPost]
public IActionResult Create([FromBody] CreateOrderRequest request)
{
// request is NULL — the body was already consumed upstream
}
With [ApiController] you get an automatic 400 saying the body is required, which at least
points somewhere. Without it, you get a null reference deeper in your code.
The middleware works and breaks the application. That is what makes it a good interview question.
How it works¶
The simple version — EnableBuffering¶
app.Use(async (context, next) =>
{
context.Request.EnableBuffering(); // ← swap in a re-readable stream
using var reader = new StreamReader(
context.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
leaveOpen: true); // ← do NOT dispose the body stream
var body = await reader.ReadToEndAsync();
logger.LogInformation("Body: {Body}", body);
context.Request.Body.Position = 0; // ← REWIND for the next reader
await next();
});
Three details, and all three are required:
EnableBuffering() replaces Request.Body with a FileBufferingReadStream, which keeps
what it reads so the stream becomes seekable.
leaveOpen: true stops StreamReader's disposal from closing the body stream. Without it
the stream is disposed and model binding throws ObjectDisposedException.
Body.Position = 0 rewinds. EnableBuffering alone only makes rewinding possible — you
still have to do it. Forget this and the symptom is identical to not buffering at all, which
makes it maddening to debug.
How it actually works — where the buffer lives¶
FileBufferingReadStream buffers in memory up to a threshold, then spills to a temp file:
context.Request.EnableBuffering(
bufferThreshold: 1024 * 100, // 100 KB in memory
bufferLimit: 1024 * 1024 * 10); // 10 MB hard ceiling — throws beyond
Defaults are a 30 KB threshold and no limit.
The design is sensible: small bodies stay in memory, large ones go to disk rather than exhausting RAM. But both have costs.
⚠️ The memory cost. Buffering every request means holding every request body in memory simultaneously. At 500 requests per second with 50 KB bodies, that is roughly 25 MB of live allocation churning constantly — straight into GC pressure (3.4).
⚠️ The disk cost. Bodies above the threshold write to a temp file. That is disk IO on every large request, and in a container with a read-only or memory-backed filesystem it can fail outright.
⚠️ The denial-of-service angle. Buffering with no bufferLimit lets an attacker send large
bodies to force allocation. Always set a limit, and keep Kestrel's MaxRequestBodySize sensible
(4.9).
The deeper detail — don't buffer everything¶
The right instinct is to buffer selectively:
app.Use(async (context, next) =>
{
var shouldLog =
context.Request.ContentLength is > 0 and < 10_000 && // small only
context.Request.ContentType?.Contains("json") == true && // JSON only
context.Request.Path.StartsWithSegments("/api"); // API only
if (!shouldLog)
{
await next(); // no buffering — no cost at all
return;
}
context.Request.EnableBuffering();
// ... read, log, rewind ...
await next();
});
And ask whether you need the body at all. Most of the time the answer is no:
- Debugging a specific problem? Enable it temporarily, behind a config flag.
- Auditing? Log the bound model from a filter instead — it is typed, and the framework did the parsing (12.8).
- Diagnosing failures only? Buffer only when the response status indicates an error.
⚠️ Logging bodies is a data-protection problem¶
Request bodies contain passwords, card numbers, personal data and tokens. Logging them wholesale means writing all of it to a log aggregator that many people can read and that is retained for months.
At minimum, redact:
private static readonly string[] SensitiveKeys =
["password", "token", "secret", "cardNumber", "ssn", "apiKey"];
private static string Redact(string json)
{
try
{
var node = JsonNode.Parse(json);
if (node is JsonObject obj)
{
foreach (var key in SensitiveKeys)
{
var match = obj.FirstOrDefault(p =>
p.Key.Contains(key, StringComparison.OrdinalIgnoreCase));
if (match.Key is not null)
obj[match.Key] = "***REDACTED***";
}
}
return node?.ToJsonString() ?? json;
}
catch
{
return "[unparseable body — not logged]"; // never log raw on failure
}
}
Note the catch: if the body will not parse, log nothing rather than dumping raw bytes that might contain anything. See 18.10.
Code¶
A realistic body-logging middleware that is safe to run in production:
internal class BodyLoggingMiddleware(
RequestDelegate next,
ILogger<BodyLoggingMiddleware> logger,
IOptions<BodyLoggingOptions> options)
{
private readonly BodyLoggingOptions _options = options.Value;
public async Task InvokeAsync(HttpContext context)
{
if (!ShouldCapture(context))
{
await next(context);
return;
}
context.Request.EnableBuffering(
bufferThreshold: _options.BufferThresholdBytes,
bufferLimit: _options.MaxBodyBytes);
string body;
using (var reader = new StreamReader(
context.Request.Body, Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
leaveOpen: true))
{
body = await reader.ReadToEndAsync(context.RequestAborted);
}
context.Request.Body.Position = 0; // ESSENTIAL — rewind
await next(context);
// Log only when something went wrong, to keep volume down
if (context.Response.StatusCode >= 400)
{
logger.LogWarning(
"Request {Method} {Path} failed with {Status}. Body: {Body}",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
Redact(body));
}
}
private bool ShouldCapture(HttpContext context) =>
_options.Enabled &&
context.Request.ContentLength is > 0 &&
context.Request.ContentLength <= _options.MaxBodyBytes &&
context.Request.ContentType?.Contains("json", StringComparison.OrdinalIgnoreCase) == true;
}
Four production-shaped decisions worth explaining:
- Config-driven
Enabledflag, so it can be switched on to investigate and off again without a deploy. - A size ceiling, so a large upload cannot force a large allocation.
- Only logs on failure, which cuts volume enormously while keeping the diagnostic value.
- Redaction, because request bodies contain credentials.
Response bodies are harder¶
Reading the response body requires swapping the stream entirely, because responses have no
EnableBuffering:
var original = context.Response.Body;
using var buffer = new MemoryStream();
context.Response.Body = buffer;
await next(context);
buffer.Position = 0;
var responseText = await new StreamReader(buffer).ReadToEndAsync();
buffer.Position = 0;
await buffer.CopyToAsync(original); // MUST copy it back
context.Response.Body = original;
⚠️ This buffers the entire response in memory, which breaks streaming endpoints and file downloads — a 500 MB file download becomes 500 MB of RAM. Response logging is worth avoiding unless you genuinely need it and can scope it tightly.
Interview questions¶
Q: Why does reading the request body in middleware break model binding?
Because Request.Body is a forward-only stream reading directly from the network socket, so
nothing is retained. Once your middleware reads it, the bytes are gone, and when model binding
runs later it finds an empty stream — so the action's parameter is null. With [ApiController]
that surfaces as an automatic 400 saying the body is required; without it you get a null
reference somewhere deeper. What makes it a nasty bug is that the middleware itself works
perfectly and only breaks something else.
Q: How do you read the body without breaking things?
Call Request.EnableBuffering() first, which swaps in a FileBufferingReadStream that retains
what it reads and is therefore seekable. Then read it, and critically set Body.Position = 0
afterwards to rewind, because EnableBuffering only makes rewinding possible — it does not do
it for you. You also need leaveOpen: true on the StreamReader, otherwise disposing the
reader closes the body stream and model binding throws ObjectDisposedException.
Q: What does buffering cost?
Memory, or disk. FileBufferingReadStream keeps up to a threshold in memory — 30 KB by default
— and spills beyond that to a temporary file. So buffering every request means holding every
request body in memory concurrently, which at a few hundred requests per second is significant
GC pressure, and larger bodies mean disk IO on every request. There is also a denial-of-service
angle: without a bufferLimit, an attacker can send large bodies to force allocation. So I
would buffer selectively — by path, content type and size — rather than globally.
Q: Would you log request bodies in production?
Reluctantly and narrowly. Bodies contain passwords, card numbers, tokens and personal data, and logging them writes all of that to an aggregator that is widely readable and retained for months. If I needed it I would gate it behind a configuration flag so it can be switched on to investigate and off again, cap the size, log only when the response indicates a failure, and redact known sensitive fields — falling back to logging nothing rather than raw bytes if the body will not parse. Often the better answer is to log the bound model from an action filter instead, since that is typed and the framework has already parsed it.
Traps ⚠️¶
- Reading the body without
EnableBufferingbreaks model binding, and the middleware itself looks fine. - Forgetting
Body.Position = 0produces the exact same symptom as not buffering at all. - Forgetting
leaveOpen: truedisposes the stream and causesObjectDisposedExceptionlater. - Buffering every request costs memory or disk on every request.
- No
bufferLimitis a denial-of-service vector. - Logging bodies leaks credentials and personal data into your log system.
- Buffering the response breaks streaming and large downloads.
- Reading the body of a
GETis pointless — there usually is not one; checkContentLength.
Related¶
- 5.8 HttpContext —
RequestandResponse - 5.14 Logging middleware — where this is normally used
- 11.2 How model binding works — who reads the body next
- 11.9 File uploads — streaming large bodies
- 18.10 What not to log — the redaction argument
- 12.8 Practical filters — logging the bound model instead
- 4.9 Kestrel limits —
MaxRequestBodySize