How to get custom attributes for a controller in asp.net core rc2

10,261

To get an attributes from the class you can do something the following:

typeof(youClass).GetCustomAttributes<YourAttribute>();
// or
// if you need only one attribute
typeof(youClass).GetCustomAttribute<YourAttribute>();

it will return IEnumerable<YourAttribute>.

So, within your code it will be something like:

Assembly.GetEntryAssembly()
        .GetTypes()
        .AsEnumerable()
        .Where(type => typeof(Controller).IsAssignableFrom(type))
        .ToList()
        .ForEach(d =>
        {
            var yourAttributes = d.GetCustomAttributes<YourAttribute>();
            // do the stuff
        });

Edit:

In case with CoreCLR you need to call one more method, because the API has been changed a bit:

typeof(youClass).GetTypeInfo().GetCustomAttributes<YourAttribute>();
Share:
10,261
StackOverflow4855
Author by

StackOverflow4855

Updated on July 24, 2022

Comments

  • StackOverflow4855
    StackOverflow4855 almost 2 years

    I have created a custom attribute :

    [AttributeUsage(AttributeTargets.Method| AttributeTargets.Class)]
    public class ActionAttribute : ActionFilterAttribute
    {
        public int Id { get; set; }
        public string Work { get; set; }
    }
    

    my controller :

    [Area("Administrator")]
    [Action(Id = 100, Work = "Test")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
    

    my code : i use reflection to find all Controllers in the current assembly

     Assembly.GetEntryAssembly()
             .GetTypes()
             .AsEnumerable()
             .Where(type => typeof(Controller).IsAssignableFrom(type))
             .ToList()
             .ForEach(d =>
             {
                 // how to get ActionAttribute ?
             });
    

    is it possible to read all the ActionAttribute pragmatically?

  • StackOverflow4855
    StackOverflow4855 almost 8 years
    'Type' does not contain a definition for 'GetCustomAttributes'
  • Sander Visser
    Sander Visser almost 7 years
    Assembly.GetEntryAssembly() will get the assembly that is used as entry. So the behavior will be different in as example your unit tests.