Testing the response body of middleware in ASP.NET Core
Testing custom middleware in ASP.NET Core is very easy (e.g. for the response status code), but it’s a bit tricky if you want to test the response body because DefaultHttpContext uses a Null-Stream for the body and thus is always empty. Creating an implementation of HttpContext is way too much overhead, but you can use a custom Stream object for the response body of DefaultHttpContext . Here is how you do it. // use this memory stream for the response body var responseBodyStream = new MemoryStream(); var context = new DefaultHttpContext(); context.Features.Get<IHttpResponseFeature>().Body = responseBodyStream; var middleware = new MyMiddleware(async (c) => { await Task.Delay(0); }); await middleware.Invoke(context); // reset the position responseBodyStream.Position = 0; // read the body string bodyContent = new StreamReader(context.Response.Body).ReadToEnd(); The trick is to access the IHttpResponseFeature of the DefaultHttpContext and to use a custom Memo...