How to get all action names from a controller

后端 未结 4 1148
逝去的感伤
逝去的感伤 2021-02-04 22:20

How could I write code to get all the action names from a controller in asp.net MVC?

I want to automatically list all the action names from a controller.

Does an

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 22:41

    I've been wrestling with this question for a while now, and I believe I've come up with a solution that should work most of the time. It involves getting a ControllerDescriptor for the controller in question, and then checking each ActionDescriptor returned by ControllerDescriptor.GetCanonicalActions().

    I ended up making an action that returned a partial view in my controller, but I think it's fairly easy to figure out what's going on so feel free to take the code and change it around to your needs.

    [ChildActionOnly]
    public ActionResult Navigation()
    {
        // List of links
        List NavItems = new List();
    
        // Get a descriptor of this controller
        ReflectedControllerDescriptor controllerDesc = new ReflectedControllerDescriptor(this.GetType());
    
        // Look at each action in the controller
        foreach (ActionDescriptor action in controllerDesc.GetCanonicalActions())
        {
            bool validAction = true;
    
            // Get any attributes (filters) on the action
            object[] attributes = action.GetCustomAttributes(false);
    
            // Look at each attribute
            foreach (object filter in attributes)
            {
                // Can we navigate to the action?
                if (filter is HttpPostAttribute || filter is ChildActionOnlyAttribute)
                {
                    validAction = false;
                    break;
                }
            }
    
            // Add the action to the list if it's "valid"
            if (validAction)
                NavItems.Add(action.ActionName);
        }
    
        return PartialView(NavItems);
    }
    

    There are probably more filters to be looking out for, but for now this suits my needs.

提交回复
热议问题