tags:

views:

65

answers:

3

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 anyone know how to do this?

Many thanks.

A: 

Using Reflection, would be a very good place to start.

CodeMonkey
+2  A: 

There's no generic solution for this, because I could write a custom attribute derived from ActionNameSelectorAttribute and override IsValidName with any custom code, even code that compares the name to a random GUID. There is no way for you to know, in this case, which action name the attribute will accept.

If you constrain your solution to only considering the method name or the built-in ActionNameAttribute then you can reflect over the class to get all the names of public methods that return an ActionResult and check whether they have an ActionNameAttribute whose Name property overrides the method name.

Greg Beech
Could you give me a simple example?
Daoming Yang
+1  A: 

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'll have to work more to suit your needs.

LukLed
Thank you for give an example for me.It is very helpful.
Daoming Yang