Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC get all action methods

Is there a way to get a list of all Actions Methods of my MVC 3 project?

like image 568
Mats Hofman Avatar asked Dec 04 '22 22:12

Mats Hofman


1 Answers

This will give you a dictionary with the controller type as key and an IEnumerable of its MethodInfos as value.

        var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // currently loaded assemblies
        var controllerTypes = assemblies
            .SelectMany(a => a.GetTypes())
            .Where(t => t != null
                && t.IsPublic // public controllers only
                && t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) // enfore naming convention
                && !t.IsAbstract // no abstract controllers
                && typeof(IController).IsAssignableFrom(t)); // should implement IController (happens automatically when you extend Controller)
        var controllerMethods = controllerTypes.ToDictionary(
            controllerType => controllerType,
            controllerType => controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType)));

It looks in more than just the current assembly and it will also return methods that, for example, return JsonResult instead of ActionResult. (JsonResult actually inherits from ActionResult)

Edit: For Web API support

Change

&& typeof(IController).IsAssignableFrom(t)); // should implement IController (happens automatically when you extend Controller)

to

&& typeof(IHttpController).IsAssignableFrom(t)); // should implement IHttpController (happens automatically when you extend ApiController)

and remove this:

.Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType))

Because Web API methods can return just about anything. (POCO's, HttpResponseMessage, ...)

like image 126
Moeri Avatar answered Dec 15 '22 12:12

Moeri