How can I get the list of all actions of MVC Controller by passing ControllerName?

隐身守侯 提交于 2019-12-18 12:28:25

问题


How can I get the list of all actions of Controller? I search but cannot find example/answer. I see some example recommended using reflection but I don't know how.

Here is what I am trying to do:

public List<string> ActionNames(string controllerName){




}

回答1:


You haven't told us why you need this but one possibility is to use reflection:

public 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();
}

Obviously as we know reflection is not very fast so if you intend to call this method often you might consider improving it by caching the list of controllers to avoid fetching it everytime and even memoizing the method for given input parameters.




回答2:


A slight tweak to Darin's answer. I needed this change to get this to work with code lense as it runs under a different assembly.

public static List<string> GetAllActionNames(string controllerName)
{
    var controllerType = Assembly.Load("YourAssemblyNameHere")
        .GetTypes()
        .FirstOrDefault(x => typeof(IController).IsAssignableFrom(x) 
            && x.Name.Equals(controllerName + "Controller", StringComparison.OrdinalIgnoreCase));

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


来源:https://stackoverflow.com/questions/11300327/how-can-i-get-the-list-of-all-actions-of-mvc-controller-by-passing-controllernam

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