title: Conditionally use custom middleware
body: <p>I created my custom authentication middleware in asp. net core project, and registered it as shown below:</p>
  
  <pre><code>public class MyAuthenticationMidleware
  {
      private readonly RequestDelegate _next;
  
      public ConnectAuthenticationMidleware(RequestDelegate next)
      {
          _next = next;
      }
  
      public async Task Invoke(HttpContext context)
      {
          if (!UserIsAuthenticated())
          {
              context.Response.StatusCode = 401;
              return;
          }
          ...
          await _next.Invoke(context);
      }
  }
  
  public static class MyAuthenticationMidlewareExtensions
  {
      public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder builder)
      {
          return builder.UseMiddleware&lt;MyAuthenticationMidleware&gt;();
      }
  }
  </code></pre>
  
  <p>In Startup:</p>
  
  <pre><code>    public void Configure(...)
      {
          app.UseStaticFiles();
          app.UseMyAuthentication();
          app.UseMvc();
      }
  </code></pre>
  
  <p>This works correctly - authentication middleware is run for each request. If user is not authenticated, 401 is returned. Otherwise specific mvc action is invoked.</p>
  
  <p>What I tried to do was to prevent the authentication middleware from running for some specific actions. I used <code>MapWhen</code> method to create another extension method and used it as follows:</p>
  
  <pre><code>public static class MyAuthenticationMidlewareExtensions
  {
      public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder builder)
      {
          return builder.UseMiddleware&lt;MyAuthenticationMidleware&gt;();
      }
  
      public static IApplicationBuilder UseMyAuthenticationWhen(this IApplicationBuilder builder, Func&lt;HttpContext, bool&gt; predicate)
      {
          return builder.MapWhen(predicate, applicationBuilder =&gt; applicationBuilder.UseMyAuthentication());
      }
  }
  
  public void Configure(...)
  {
      app.UseStaticFiles();
      app.UseMyAuthenticationWhen(context =&gt; context.Request.Path != "xyz");
      app.UseMvc();
  }
  </code></pre>
  
  <p>Unfortunately, this doesn't work as expected. The middleware is invoked only when path is different than "xyz", but it seems that it short-circuts the whole chain - no mvc specific actions or filters are invoked. </p>
  
  <p>Probably my understanding of <code>MapWhen</code> is incorrect. Is there any way to get the result I want?</p>