title: Rewrite the response in Owin Middleware
body: <p>In my OWIN app, I register a middleware to intercept the outcome of other middlewares down in the pipeline and if a condition is met, I need to totally change the response from whatever it is (could be <code>302</code> or <code>200</code>) to <code>403</code> (forbidden).</p>
  
  <p>There is ofcourse a not-very-clean-way and that is to manually clear all the headers, content type, etc. and set the statusCode to <code>403</code> but this feels to me a wrong approach.</p>
  
  <pre><code>public override async Task Invoke(IOwinContext context)
  {
      await this.Next.Invoke(context);
  
      if (someCondition(context))
      {
          var headers = context.Response.Headers;
          headers.Keys.ForEach(k =&gt; headers.Remove(k));
          context.Response.StatusCode = 403;
          context.Response.ContentType = string.Empty;
          context.Response.ContentLength = null;
          await context.Response.WriteAsync(string.Empty);
      }
  }
  </code></pre>
  
  <p>Plus the fact that this approach doesn't work when overwriting a <code>200</code> response (when it hits the line where we set <code>StatusCode</code>, it jumps out and flushes the response).</p>
  
  <p>I'm new to OWIN and I may be misunderstanding the way it works.</p>
  
  <p>Is there any other way you would do this?</p>