title: Set response status in ASP.NET core middleware
body: <p>I have a middleware, which hides exception from client and returns 500 error in case of any exception:</p>
  
  <pre><code>public class ExceptionHandlingMiddleware
  {
      private readonly RequestDelegate _next;
  
      public ExceptionHandlingMiddleware(RequestDelegate next)
      {
          _next = next;
      }
  
      public async Task Invoke(HttpContext context)
      {
          try
          {
              await _next.Invoke(context);
          }
          catch (Exception exception)
          {
              var message = "Exception during processing request";
              using (var writer = new StreamWriter(context.Response.Body))
              {
                  context.Response.StatusCode = 500; //works as it should, response status 500
                  await writer.WriteAsync(message);
                  context.Response.StatusCode = 500; //response status 200
              }
          }
      }
  }
  </code></pre>
  
  <p>My problem is that, if I set response status before writing body, client will see this status, but if I set status after writing message to body, client will receive response with status 200.</p>
  
  <p>Could somebody explain me why it's happening?</p>
  
  <p>P.S. I am using ASP.NET Core 1.1</p>