Search code examples
c#asp.net-mvcasp.net-mvc-controller

Getting All Controllers and Actions names in C#


Is it possible to list the names of all controllers and their actions programmatically?

I want to implement database driven security for each controller and action. As a developer, I know all controllers and actions and can add them to a database table, but is there any way to add them automatically?


Solution

  • You can use reflection to find all Controllers in the current assembly, and then find their public methods that are not decorated with the NonAction attribute.

    Assembly asm = Assembly.GetExecutingAssembly();
    
    asm.GetTypes()
        .Where(type=> typeof(Controller).IsAssignableFrom(type)) //filter controllers
        .SelectMany(type => type.GetMethods())
        .Where(method => method.IsPublic && ! method.IsDefined(typeof(NonActionAttribute)));