Get custom attributes via ActionExecutingContext from controller .Net Core

For ASP.NET Core 3+:

    var filters = context.Filters;
    // And filter it like this: 
    var filtered = filters.OfType<OurFilterType>();


Another option without needing a runtime cast:

public class MyAttribute :  Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute {
  // same content as in the question
}

By inheriting from ActionFilterAttribute, your attribute will now appear in the ActionDescriptor.FilterDescriptors collection, and you can search that:

public virtual void SetupMetadata(ActionExecutingContext filterContext)
{
    var myAttr = filterContext.ActionDescriptor
        .FilterDescriptors
        .Where(x => x.Filter is MyAttribute)
        .ToArray();
    if (myAttr.Length == 1) {
        //do something
    }
}

I'm unsure if this is dirtier or cleaner than casting to ControllerActionDescriptor, but it's an option if you control the attribute.


Hope to help others, here's what i did:

var attrib = (filterContext.ActionDescriptor as ControllerActionDescriptor).MethodInfo.GetCustomAttributes<MyAttribute>().FirstOrDefault();