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

后端 未结 2 1700
星月不相逢
星月不相逢 2020-12-29 09:40

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.

<
相关标签:
2条回答
  • 2020-12-29 10:15

    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.

    0 讨论(0)
  • 2020-12-29 10:16

    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();
    }
    
    0 讨论(0)
提交回复
热议问题