How to get all action names from the controller

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

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

Does anyone know how to do this?

Many thanks.

+3
source share
4 answers

There is no general solution for this, because I could write my own attribute obtained from ActionNameSelectorAttributeand override IsValidNamewith any custom code, even code that compares the name with a random GUID. In this case, you cannot know what action the attribute will take.

ActionNameAttribute, , , ActionResult, , ActionNameAttribute Name .

+3

, , , . ControllerDescriptor , ActionDescriptor, ControllerDescriptor.GetCanonicalActions().

, , , , .

[ChildActionOnly]
public ActionResult Navigation()
{
    // List of links
    List<string> NavItems = new List<string>();

    // 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 "valid"
        if (validAction)
            NavItems.Add(action.ActionName);
    }

    return PartialView(NavItems);
}

, , , , .

+8

You can start with:

Type t = typeof(YourControllerType);
MethodInfo[] mi = t.GetMethods();
foreach (MethodInfo m in mi)
{
    if (m.IsPublic)
        if (typeof(ActionResult).IsAssignableFrom(m.ReturnParameter.ParameterType))
            methods = m.Name + Environment.NewLine + methods;
}

You will have to work harder to meet your needs.

+2
source

Using Reflection would be a very good place to start.

0
source

Source: https://habr.com/ru/post/1721310/


All Articles