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

How to get ASP.NET Core MVC Filters from HttpContext


I'm trying to write some middleware and need to know if the current action method (if any) has a particular filter attribute, so I can change behaviour based it's existence.

So is it possible to get a filters collection of type IList<IFilterMetadata> like you do on the ResourceExecutingContext when you are implementing an IResourceFilter?


Solution

  • It's not really possible today.

    It is possible in ASP.NET Core 3.0

    app.UseRouting();
    
    
    app.Use(async (context, next) =>
    {
        Endpoint endpoint = context.GetEndpoint();
    
        YourFilterAttribute filter = endpoint.Metadata.GetMetadata<YourFilterAttribute>();
    
        if (filter != null)
        { 
    
        }
    
        await next();
    });
    
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });