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

204 result produces HttpContext response body stream flagged as writable.  #1028

@mkArtakMSFT

Description

@mkArtakMSFT

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:

  1. 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.
      }
 }
  1. 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);   
                 }
             }
         }
     }
    
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions