Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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){




}
like image 611
nannypooh Avatar asked Jul 02 '12 19:07

nannypooh


1 Answers

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.

like image 61
Darin Dimitrov Avatar answered Oct 25 '22 20:10

Darin Dimitrov