Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude route from middleware - .net core

I have 2 middlewares in the application. I want to exclude one route from those middlewares. What i have tried is creating a BuildRouter functions and apply middlewares through it but this didn't work.

public IRouter BuildRouter(IApplicationBuilder applicationBuilder)
{
    var builder = new RouteBuilder(applicationBuilder);

    builder.MapMiddlewareRoute("/api/", appBuilder => {
        appBuilder.ApplyKeyValidation();
        appBuilder.ApplyPolicyValidation();
    });

    return builder.Build();
}

And the configure method is

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseRouter(BuildRouter(app));

    app.UseHttpsRedirection();
    app.UseMvc();       
}

But this is not working.

like image 569
ThunderBolt Avatar asked Apr 13 '26 21:04

ThunderBolt


1 Answers

For middlewares, you should use app.UseWhen as opposed to app.MapWhen because MapWhen terminates the pipeline. I learned this the hard way trying to use the other answer.

It's been a while, but since I stumbled across this others might too. So, for your example:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseWhen(
        context => !context.Request.Path.StartsWithSegments("/api"),
        appBuilder =>
        {
            appBuilder.ApplyKeyValidation();
            appBuilder.ApplyPolicyValidation();
        }
    );

    app.UseHttpsRedirection();
    app.UseMvc();       
}
like image 105
vgdude999 Avatar answered Apr 16 '26 10:04

vgdude999



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!