Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Created June 8, 2019 09:28
Show Gist options
  • Save alistairjevans/766eb538401674d9061379a15bd42342 to your computer and use it in GitHub Desktop.
Save alistairjevans/766eb538401674d9061379a15bd42342 to your computer and use it in GitHub Desktop.
Buffered Middleware - allows responses to be read by the out-of-the-box arduino HTTP libraries
public class BufferMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var newContent = string.Empty;
var originalBody = context.Response.Body;
using (var newBody = new MemoryStream())
{
// We set the response body to our stream so we can read after the chain of middlewares have been called.
context.Response.Body = newBody;
await next(context);
// Reset the body so nothing from the latter middlewares goes to the output.
context.Response.Body = originalBody;
context.Response.Headers.ContentLength = newBody.Length;
context.Response.Headers.Remove("Transfer-Encoding");
// Send our modified content to the response body.
await context.Response.Body.WriteAsync(newBody.ToArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment