2

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 Answer 1

4

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; } } } 
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
I suggest using the namespace for the Area issue, since its very likely those Area controllers share a common namespace.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.