How to Find All Controller and Action

蹲街弑〆低调 提交于 2019-12-05 18:56:03

问题


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.


回答1:


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:

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.



来源:https://stackoverflow.com/questions/44455384/how-to-find-all-controller-and-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!