Search code examples
c#asp.net-coremiddleware

Setting middleware for specific controller in ASP.NET Core


I want to create a middleware that checks for a private access key header and add it to a specific ApiController in ASP.NET Core.

The only ways I found were using app.useMiddleware() or checking whether or not the request URL contained the controller route but that's not what I want to use as it seems pretty inefficient.

How else can I achieve this?


Solution

    • You can use app.UseWhen() method to apply a middleware conditionally based on the request path. For example,

      app.UseWhen(context => context.Request.Path.StartsWithSegments(“/api”), appBuilder => { appBuilder.UseMiddleware<MyMiddleware>(); });

    • You can use [MiddlewareFilter] attribute to specify a middleware pipeline class on your controller or action. For example, [MiddlewareFilter(typeof(MyPipeline))] public class MyController : Controller { … }

    • You can use MapWhen() method to branch the request pipeline based on a predicate. For example, app.MapWhen(context => context.Request.Headers.ContainsKey(“PrivateAccessKey”), appBuilder => { app.UseMiddleware<MyMiddleware>(); });