Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the list of Controllers/Actions in an ASP.NET MVC application

We know that behind the scenes, the ASP.NET MVC framework will use reflection to determine what controllers/actions are available to be executed, based on which classes derive from System.Web.Mvc.Controller and, of those classes, which methods return an ActionResult object.

To my question - is it possible to access this list of controllers/actions from within my MVC application?

(I could do it myself, by using reflection on the current assembly, but if the list has already been built by ASP.NET MVC, I'd rather re-use that effort than re-invent the wheel myself.)

like image 470
Jonathan Avatar asked Apr 26 '09 08:04

Jonathan


2 Answers

new ReflectedControllerDescriptor(typeof(TController)).GetCanonicalActions() will return a collection of ActionDescriptor objects showing all the actions on the controller. It's not smart enough to understand things like selection attributes or naming attributes, so not every action it returns is guaranteed to be web-callable. But if you need to execute the actions directly, you can call ActionDescriptor.Execute() on any action of interest to you.

like image 161
Levi Avatar answered Nov 16 '22 02:11

Levi


This is done in an internal class in the System.Web.Mvc assembly called System.Web.Mvc.ControllerTypeCache.

By the way, action methods are not required to return ActionResult. They can return void happily, for instance.

like image 29
mmx Avatar answered Nov 16 '22 00:11

mmx