The final technique we will be covering here is response buffering. Normally, a web server streams a response, meaning that it sends a response as soon as it has its chunks. Another option is to get all these chunks, combine them, and send them at once: this is called buffering.
Buffering offers some advantages: it can result in better performance and offer the ability to change the contents (including headers) before they are sent to the client.
Microsoft offers buffering capabilities through the Microsoft.AspNetCore.Buffering NuGet package. Using it is simple—for example, you can use it in a middleware lambda:
app.UseResponseBuffering();
app.Run(async (ctx) =>
{
ctx.Response.ContentType = "text/html";
await ctx.Response.WriteAsync("Hello, World!);
ctx.Response.Headers.Clear();
ctx.Response.Body.SetLength(0);
ctx.Response.ContentType = "text/plain";
await ctx.Response.WriteAsync("...