.NET MVC: Counting Action methods in web applicati

2019-06-26 19:51发布

问题:

We've got a huge ASP.NET MVC 3 application. We need to count how many public methods we have in classes where currentClass is System.Web.Mvc.Controller.

Any class that meets this criteria will have a base namespace of 'AwesomeProduct.Web', but there's no guarantee beyond that what namespace these classes may fall under, or how many levels of depth there are.

What's the best way to figure this out?

回答1:

Some reflection and LINQ like this should do it

var actionCount = typeof(/*Some Controller Type In Your MVC App*/)
                    .Assembly.GetTypes()
                    .Where(t => typeof(Controller).IsAssignableFrom(t))
                    .Where(t => t.Namespace.StartsWith("AwesomeProduct.Web"))
                    .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                    .Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType))
                    .Where(m => !m.IsAbstract)
                    .Where(m => m.GetCustomAttribute<NonActionAttribute>() == null)
                    .Count();

This does not cater for async controller actions.