Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core check route attribute in middleware

Tags:

asp.net-core

I'm trying to build some ASP.Net core middleware.

It needs see if the current route is marked as [Authorize].

eg:

public async Task Invoke(HttpContext context)
{
    if(context.Request.Path.Value.StartsWith("/api"))
    {
        // check if route is marked as [Authorize]
        // and then do some logic
    }

    await _next.Invoke(context);
}

Does anyone know how this could be achieved or if it's even possible?

If not, what would be a good alternative approach?

like image 827
sf. Avatar asked Aug 03 '17 22:08

sf.


People also ask

What is attribute routing in ASP.NET Core?

With attribute-based routing, we can use C# attributes on our controller classes and on the methods internally in these classes. These attributes have metadata that tell ASP.NET Core when to call a specific controller. It is an alternative to convention-based routing.

What is IApplicationBuilder in .NET Core?

IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.

Where are routes defined in .NET Core?

Routing uses a pair of middleware, registered by UseRouting and UseEndpoints: UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app, and selects the best match based on the request. UseEndpoints adds endpoint execution to the middleware pipeline.

How do I use MapControllerRoute?

MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); The route names give the route a logical name. The named route can be used for URL generation. Using a named route simplifies URL creation when the ordering of routes could make URL generation complicated.


1 Answers

I believe it can be achieved in a middleware class via:

var hasAuthorizeAttribute = context.Features.Get<IEndpointFeature>().Endpoint.Metadata
                .Any(m => m is AuthorizeAttribute);
like image 146
HansElsen Avatar answered Sep 21 '22 15:09

HansElsen