Search code examples
c#asp.net-coreasp.net-core-middleware

Registering a middleware while using MapWhen for branching to run it just for a set of endpoints


I need to run two middlewares for all my endpoints but the ones under /accounts/*.

I use this in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddControllers();
}

and the configure method looks like:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUserService  userService)
{
    app.UseCors(builder => builder
        //.AllowAnyOrigin()
        .SetIsOriginAllowed((host) => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());

    app.UseRouting();

    app.UseAuthentication();

    //THIS IS WHAT I JUST ADDED TO SUPPORT THE BRANCHING OF ROUTES
    app.MapWhen(context =>
    {
        return !context.Request.Path.StartsWithSegments("/accounts");
    }, appBuilder =>
    {
        appBuilder.UseMiddleware<TenantProviderMiddleware>();
        appBuilder.UseMiddleware<UserClaimsBuilderMiddleware>();
    });

    //app.UseMiddleware<TenantProviderMiddleware>();
    //app.UseMiddleware<UserClaimsBuilderMiddleware>();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<VehicleHub>("/vehicle-hub");
        endpoints.MapControllers();
    });

 }

But I'm getting the following error:

System.InvalidOperationException: The request reached the end of the pipeline without executing the endpoint: 'WebAPI.Controllers.VehiclesController.Get (WebApi)'. Please register the EndpointMiddleware using 'IApplicationBuilder.UseEndpoints(...)' if using routing.

From the error I understand that I should be using UseEndpoints instead of UseMiddleware in the MapWhen method but can't get it right.

How should I register the middlewares then?


Solution

  • It looks like you need UseWhen, which, according to the docs:

    ...branches the request pipeline based on the result of the given predicate. Unlike with MapWhen, this branch is rejoined to the main pipeline if it doesn't short-circuit or contain a terminal middleware

    Because you're using MapWhen, both UseAuthorization and UseEndpoints have no affect for your /accounts/ paths. The error you've shown is because the Endpoints middleware doesn't run in this scenario.