【问题标题】:Scan for all actions in the site扫描站点中的所有操作
【发布时间】:2013-04-06 23:22:21
【问题描述】:

如何为网站中的所有操作创建操作链接?
我想将这些操作链接放入菜单系统中。

我希望我能做类似的事情

foreach controller in controllers {
    foreach action in controller{
        stringbuilder.writeline(
            "<li>"+actionlink(menu, action, controller)+"<li>"
        );
    }
}

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 navigation


    【解决方案1】:

    这是我的看法:

    var controllers = Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(Controller))).ToList();
    var controlList = controllers.Select(controller =>
                                         new
                                         {
                                             Actions = GetActions(controller),
                                             Name = controller.Name,
                                         }).ToList();
    

    方法GetActions如下:

    public static List<String> GetActions(Type controller)
    {
        // List of links
        var items = new List<String>();
    
        // Get a descriptor of this controller
        var controllerDesc = new ReflectedControllerDescriptor(controller);
    
        // Look at each action in the controller
        foreach (var action in controllerDesc.GetCanonicalActions())
        {
            // Get any attributes (filters) on the action
            var attributes = action.GetCustomAttributes(false);
    
            // Look at each attribute
            var validAction =
                attributes.All(filter => !(filter is HttpPostAttribute) && !(filter is ChildActionOnlyAttribute));
    
            // Add the action to the list if it's "valid"
            if (validAction)
               items.Add(action.ActionName);
        }
        return items;
    }
    

    如果您需要一个菜单​​系统,请查看MVC Sitemap Provider,它可以让您根据您在成员资格实施中定义的角色完全控制要呈现的内容。

    【讨论】:

    • 我看过provider,可能还需要多看一点,但是貌似需要通过xml来定义菜单?
    • 是的,您必须使用 XML 定义菜单。但是您可以使用我提供的代码来获取初始列表(您仍然需要定义哪些角色可以访问哪些操作)
    • 我们有一个基于权限的自定义授权,允许用户定义它。它是一个多租户系统,因此它要么必须基于表,要么基于约定。我们试图让后者发挥作用。
    • 有效,但前提是我将 Assembly.GetCallingAssembly() 更改为 Assembly.GetExecutingAssembly()
    【解决方案2】:

    这是如何从控制器 Asp.net Mvc: List all the actions on a controller with specific attributeAccessing the list of Controllers/Actions in an ASP.NET MVC application 获取所有操作的方法 为了实现您的目标,您应该使用Assembly.GetExportedTypes() 找到项目中的所有控制器,并仅过滤ControllerBase 的子类,并为每个控制器从第二个链接调用new ReflectedControllerDescriptor(typeof(TController)).GetCanonicalActions()

    【讨论】:

    • 谢谢,我会在星期一检查这些。
    • 这些帖子仅适用于当前控制器。 ahmed 的帖子更全面,所以我将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2013-04-15
    相关资源
    最近更新 更多