如何通过传递 ControllerName 获取 MVC Controller 的所有操作列表? [英] How can I get the list of all actions of MVC Controller by passing ControllerName?

查看:14
本文介绍了如何通过传递 ControllerName 获取 MVC Controller 的所有操作列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取Controller所有动作的列表?我搜索但找不到示例/答案.我看到一些推荐使用反射的例子,但我不知道如何.

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.

这是我想要做的:

public List<string> ActionNames(string controllerName){




}

推荐答案

你还没有告诉我们你为什么需要这个,但一种可能性是使用反射:

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.

这篇关于如何通过传递 ControllerName 获取 MVC Controller 的所有操作列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆