As my application initializes, I want to create a registry of any MVC action whose method has a certain CustomAttribute on it. I want this registry to keep track of the MVC Area, Controller, and Action. I could require the person adding the attribute to specify this information, but it seems like I should be able to figure out this information based on the MethodInfo: basically the reverse of what happens when the ActionLink method is called. How can I do this?
+1
A:
Search through the assembly for every Controller
, then search through all the methods to find those with a certain attribute on them.
// current assembly -> all types that have basetype controller -> grab methods
foreach(var type in System.Reflection.Assembly.GetCallingAssembly().GetTypes().Where(t=>
typeof(Controller).IsAssignableFrom(t))))
{
foreach(var methodInfo in type.GetMethods())
{
if (methodInfo.GetCustomAttributes(typeof(MyAttribute), false).Count() > 0)
{
var action = methodInfo.Name;
var controller = type.Name;
}
}
}
Jan Jongboom
2010-09-14 16:19:40
It's the "// Do Something" that I'm trying to ask here. Assume you have the MethodInfo: now how do you get the MVC Area, Controller, and Action name?
StriplingWarrior
2010-09-14 16:25:27
Changed my sample. Don't know about the area though: an area isn't tightly coupled to a controller action or what? I guess you want to look in `RouteCollection` if there is an area with the controller name and the action you have in the variables.
Jan Jongboom
2010-09-14 16:36:31
I suggest using the namespace for the Area issue, since its very likely those Area controllers share a common namespace.
eglasius
2010-09-14 22:04:43