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
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.
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.
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<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'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.
Using Reflection, would be a very good place to start.