This repository was archived by the owner on Nov 20, 2018. It is now read-only.

Description
From @mfolker-sage on July 30, 2018 9:20
Bug
The HttpContext in middleware has response body stream flagged as writeable when a 204 response is returned. A 204 should not be writable has the status code denotes no content. When you try to write to the response body stream an error is thrown as expected.
Steps to reproduce:
- Add a middleware class with the following code and an endpoint that returns a 204 status.
public async Task Invoke(HttpContext context)
{
_logger.LogInformation("Invoking vanilla middleware middleware.");
await _next(context);
_logger.LogInformation ($"Status code {context.Response.StatusCode}");
if (context.Response.Body.CanWrite)
{
//Write something to the body.
}
}
-
Write something to the body, for example,
public async Task Invoke(HttpContext context)
{
var bodyStream = context.Response.Body;
using (var responseBodyStream = new MemoryStream())
{
using (var reader = new StreamReader(responseBodyStream))
{
context.Response.Body = responseBodyStream;
await _next(context);
responseBodyStream.Seek(0, SeekOrigin.Begin);
var responseBodyText = reader.ReadToEnd();
var messageObjToLog = new { responseBody = responseBodyText, statusCode = context.Response.StatusCode };
_logger.LogInformation(JsonConvert.SerializeObject(messageObjToLog));
if (context.Response.CanWrite)
{
responseBodyStream.Seek(0, SeekOrigin.Begin);
await responseBodyStream.CopyToAsync(bodyStream);
}
}
}
}
-
When you return a 204 status code you will notice context.Response.CanWrite == true and therefore the lines copies back to it throws an error.
Description of the problem:
In instances of 204 status codes the context.Response.CanWrite should be false.
Microsoft.AspNetCore.All version 2.0.3
Copied from original issue: aspnet/Mvc#8171