我怎样才能得到MVC控制器的所有动作通过传递ControllerName名单? [英] How can I get the list of all actions of MVC Controller by passing ControllerName?

查看:221
本文介绍了我怎样才能得到MVC控制器的所有动作通过传递ControllerName名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能获得控制器的所有操作的列表?我搜索,但无法找到例子/答案。我看到使用反射推荐的一些例子,但我不知道怎么办。

下面就是我要做的:

 公开名单<串GT; ActionNames(字符串controllerName){
}


解决方案

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

 公开名单<串GT; ActionNames(字符串controllerName)
{
    VAR类型=
        从在AppDomain.CurrentDomain.GetAssemblies()
        从吨a.GetTypes()
        其中,typeof运算(一个IController).IsAssignableFrom(T)及和放大器;
                string.Equals(controllerName +控制器,t.Name,StringComparison.OrdinalIgnoreCase)
        选择吨;    变种controllerType = types.FirstOrDefault();    如果(controllerType == NULL)
    {
        返回Enumerable.Empty&所述;串方式>()了ToList();
    }
    返回新ReflectedControllerDescriptor(controllerType)
        。.GetCanonicalActions()选择(X => x.ActionName)
        .ToList();
}

显然,因为我们知道反思是不是非常快,所以如果你打算调用这个方法的时候,你可能会考虑通过缓存控制器的列表,以避免它取每次连的memoizing~~V 方法对于给定的输入参数。

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




}

解决方案

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.

这篇关于我怎样才能得到MVC控制器的所有动作通过传递ControllerName名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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