14

How to find all controllers and actions with its attribute in dotnet core? In .NET Framework I used this code:

public static List<string> GetControllerNames()
{
    List<string> controllerNames = new List<string>();
    GetSubClasses<Controller>().ForEach(type => controllerNames.Add(type.Name.Replace("Controller", "")));
    return controllerNames;
}
public static List<string> ActionNames(string controllerName)
{
    var types =
        from a in AppDomain.CurrentDomain.GetAssemblies()
        from t in a.GetTypes()
        where typeof(IController).IsAssignableFrom(t) &&
            string.Equals(controllerName + "Controller", t.Name, StringComparison.OrdinalIgnoreCase)
    select t;

    var controllerType = types.FirstOrDefault();

    if (controllerType == null)
    {
        return Enumerable.Empty<string>().ToList();
    }
    return new ReflectedControllerDescriptor(controllerType)
       .GetCanonicalActions().Select(x => x.ActionName).ToList();
}

but its not working in dotnet core.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272

1 Answers1

19

How about injecting IActionDescriptorCollectionProvider to your component that needs to know these things? It's in the Microsoft.AspNetCore.Mvc.Infrastructure namespace.

This component gives you every single action available in the app. Here is an example of the data it provides:

Action descriptor collection provider data sample

As a bonus, you can also evaluate all of the filters, parameters etc.


As a side note, I suppose you could use reflection to find the types that inherit from ControllerBase. But did you know you can have controllers that don't inherit from it? And that you can write conventions that override those rules? For this reason, injecting the above component makes it a lot easier. You don't need to worry about it breaking.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • thanks for your help. this https://stackoverflow.com/questions/39276763/getting-controller-details-in-asp-net-core and https://stackoverflow.com/questions/31874733/how-to-read-action-methods-attributes-in-asp-net-core-mvc help me solve it :) –  Jun 09 '17 at 13:54
  • For those using NSwag, leverage the plumbing you've already provided with: `Program.CreateHostBuilder(new string[0]).Build().Services.GetRequiredService()` – Peter L Feb 25 '21 at 06:53