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).
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)));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With