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?
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.
IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.
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.
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.
I believe it can be achieved in a middleware class via:
var hasAuthorizeAttribute = context.Features.Get<IEndpointFeature>().Endpoint.Metadata
.Any(m => m is AuthorizeAttribute);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With