Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all ASP.NET MVC public action methods that accept a string as a parameter

I am attempting to use Nitriq to get a list of all of the public actions in my project that accept a string as input.

Here is what I have tried:

var stringType = Types.Where(t => t.FullName == "System.String").Single();
var arTypes = Types.Where(t => t.FullName == "System.Web.Mvc.ActionResult").Single().DerivedTypes;

var results = 
from m in Methods
let DerivesFromAR = arTypes.Contains(m.ReturnType)
where m.ParameterTypes.Contains(stringType) && DerivesFromAR
select new { m.MethodId, m.Name, m.FullName };

I am using Nitriq because this seems like an ideal task for it, but I am open to other approaches (preferably not searching all of my methods by hand).

like image 317
Matthew Nichols Avatar asked Dec 27 '22 06:12

Matthew Nichols


2 Answers

You shouldn't be looking for types derived from System.Web.Mvc.ActionResult, but for types derived from System.Web.Mvc.Controller as those classes contain methods that return action results.

Solution using System.Reflection and System.Linq, use from within of assembly that is supposed to be scanned

var controllerType = typeof(System.Web.Mvc.Controller);
var actionResultType = typeof(System.Web.Mvc.ActionResult);
var parameterType = typeof(string);

// find all controllers by checking their class
var controllers = Assembly.GetCallingAssembly().GetTypes().Where(t => controllerType.IsAssignableFrom(t));
// find all actions by checking their return type and parameter type
var actions = controllers.SelectMany(c => c.GetMethods()).Where(m => actionResultType.IsAssignableFrom(m.ReturnType) && m.GetParameters().Any(p => parameterType.IsAssignableFrom(p.ParameterType)));   
like image 128
Lukáš Novotný Avatar answered Dec 29 '22 19:12

Lukáš Novotný


I won't have a chance to check for sure until later today, but I think

var stringType = Types.Where(t => t.FullName == "System.Object").Single();

should be

var stringType = Types.Where(t => t.FullName == "System.String").Single();

It looks like right now you're looking for actions that take objects instead of actions that take strings.

like image 42
Chris W. Avatar answered Dec 29 '22 20:12

Chris W.