title: Middleware works in program.cs, but not when moved to it's own class
body: <p>I'm using asp.net core 6, in my program.cs I have the following middleware, which is used to redirect the user when the statuscode is 404.</p>
  <pre><code>app.Use(async (ctx, next) =&gt;
  {
      await next();
  
      if (ctx.Response.StatusCode == 404 &amp;&amp; !ctx.Response.HasStarted)
      {
          string originalPath = ctx.Request.Path.Value;
          ctx.Items[&quot;originalPath&quot;] = originalPath;
          ctx.Request.Path = &quot;/error/NotFound404&quot;;
          await next();
      }
  });
  </code></pre>
  <p>This all works fine, but I want to clean up my program.cs a bit, so I decided to put this code in it's own class like this:</p>
  <pre><code>public class NotFoundMiddleware
  {
      private readonly RequestDelegate _next;
      public NotFoundMiddleware(RequestDelegate next)
      {
          _next = next;
      }
      public async Task InvokeAsync(HttpContext httpContext)
      {
  
          if (httpContext.Response.StatusCode == 404 &amp;&amp; !httpContext.Response.HasStarted)
          {
              string originalPath = httpContext.Request.Path.Value;
              httpContext.Items[&quot;originalPath&quot;] = originalPath;
              httpContext.Request.Path = &quot;/error/NotFound404&quot;;
          }
          
          await _next(httpContext);
      }
  }
  
  public static class NotFoundMiddlewareExtensions
  {
      public static IApplicationBuilder CheckNotFound(this IApplicationBuilder builder)
      {
          return builder.UseMiddleware&lt;NotFoundMiddleware&gt;();
      }
  }
  </code></pre>
  <p>And in my program.cs</p>
  <pre><code>app.CheckNotFound(); // on the same place the upp.Use... was before.
  </code></pre>
  <p>But then it doesn't work anymore.</p>
  <p>I went through my code using breakpoints. and the InvokeAsync gets called on each request,
  The problem is that the <code>httpContext.Response.StatusCode</code> always returns <code>200</code>.</p>