.NET › ASP.NET Core Middleware & Request Pipeline

How does the middleware pipeline interact with asynchronous streaming responses, and what precautions are needed?

Advanced

Answer

Since middleware runs both before and after calling next() (which may write directly to the response stream inside the endpoint handler), middleware that reads or buffers the response body (e.g., for logging or compression) must be careful with streaming scenarios -- reading the full response into memory before it's sent can break true streaming (like Server-Sent Events) by defeating its purpose, so such middleware often needs to wrap the response stream rather than buffer it entirely.
public class ResponseLoggingMiddleware {
    public async Task InvokeAsync(HttpContext context, RequestDelegate next) {
        var originalBody = context.Response.Body;
        using var buffer = new MemoryStream();
        context.Response.Body = buffer;  // caution: breaks true streaming if not handled carefully
        await next(context);
        buffer.Seek(0, SeekOrigin.Begin);
        await buffer.CopyToAsync(originalBody);
    }
}
Real-world example A team debugging why their Server-Sent Events endpoint stopped streaming in real time discovers a response-logging middleware was fully buffering the response before forwarding it, defeating the whole point of streaming.

Common follow-ups: How would you rewrite this middleware to support true streaming while still logging?;What's the performance cost of response buffering middleware?