【问题标题】:How can I get the list of all actions of MVC Controller by passing ControllerName?如何通过传递 ControllerName 获取 MVC Controller 的所有操作列表?
【发布时间】:2012-07-02 19:58:19
【问题描述】:

如何获取 Controller 的所有操作列表?我搜索但找不到示例/答案。我看到一些建议使用反射的示例,但我不知道如何。

这是我想要做的:

public List<string> ActionNames(string controllerName){




}

【问题讨论】:

  • 我要在这里发表评论,因为它很笼统。因为您尝试做的事情(控制器操作名称)不是应该做的事情。可能有多个具有相同名称的操作,有些可能仅是 Ajax 等等。您的权限应该基于控制器操作以外的其他内容。

标签: asp.net-mvc controller action


【解决方案1】:

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

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

显然我们知道反射不是很快,所以如果你打算经常调用这个方法,你可以考虑通过缓存控制器列表来改进它,以避免每次都获取它,甚至memoizing给定输入参数的方法。

【讨论】:

  • 谢谢!!!在我的应用程序中,我需要为管理员用户创建权限页面。管理员将从下拉列表中选择一个控制器名称,然后操作列表将根据所选控制器名称动态显示。然后将这些值分配给用户/角色。
  • 我在“from t in a.GetTypes() - 无法加载一个或多个请求的类型”上收到错误消息。
  • 值得指出的是,ReflectedControllerDescriptor 的 GetCanonicalActions 方法将为控制器上的每个公共方法返回一个 ActionDescriptor,包括不是操作的方法。它也忽略了 NonActionAttribute。
  • 当动作被自定义[ActionName]装饰时不起作用
【解决方案2】:

对达林的回答稍作调整。我需要进行此更改以使其与 code lense 一起使用,因为它在不同的程序集下运行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2018-02-21
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    相关资源
    最近更新 更多