tags:

views:

107

answers:

2

The title says it all.

If I have an instance of ActionExecutingContext how might I get the MethodInfo of the action in question?

+2  A: 

ActionExecutingContext has a property ActionDescriptor.

If the return type is actually a ReflectedActionDescriptor you should be able to cast is as such. Once you have a ReflectedActionDescriptor...

http://msdn.microsoft.com/en-us/library/system.web.mvc.reflectedactiondescriptor.aspx

... you can use it's MethodInfo property...

http://msdn.microsoft.com/en-us/library/system.web.mvc.reflectedactiondescriptor.methodinfo.aspx

You should be careful using techniques that take the action's name and use this to obtain a MethodInfo. In many cases the name of an action will be the same as the method name on the controller, but this will not always be the case. If you use the ActionName attribute on the controller's method then you can explicitly set the name of the action. In addition, it is possible to have 2 methods with different signatures, both with the same action name. This is common when you have a GET and POST version of the same action (e.g. the Register and LogOn actions present in a brand new ASP.NET MVC project within AccountController.cs).

Martin Peck
The MVC framework itself has no other types that inherit `ActionDescriptor`.
SLaks
Indeed. So, you should always get a ReflectedActionDescriptor and my approach will work. I used the word "if" as insurance for future versions of MVC, and to suggest that the code to cast the ActionDescriptor should be written with this possibility in mind.
Martin Peck
+1  A: 

Try Controller.GetType.GetMethod(actionExecutingContext.ActionName).

If your code is directly in the action, you could also call MethodBase.GetCurrentMethod().

SLaks
How would the GetMethod solution work where there are multiple methods with the same name? For example, two overloads to LogOn or Register (one accepting POST and the other GET). Also, it's possible to use the ActionName attribute to make the action's name very different to the method name.
Martin Peck
It wouldn't. Your answer is much better.
SLaks