Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a MethodInfo from an ActionExecutingContext?

Tags:

asp.net-mvc

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

like image 771
JoelFan Avatar asked Dec 29 '09 00:12

JoelFan


3 Answers

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

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

like image 97
SLaks Avatar answered Oct 20 '22 05:10

SLaks


I needed to get the MethodInfo to fetch my custom attributes for some logging purposes.

For this specific use case I noticed that (at least in MVC5) an ActionDescriptor.GetCustomAttributes method exists, and it's properly overridden for each ActionDescroptor descendants.

Similarly, there are other related methods like GetParameters, etc.

like image 20
Zoltán Tamási Avatar answered Oct 20 '22 06:10

Zoltán Tamási


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).

like image 35
Martin Peck Avatar answered Oct 20 '22 07:10

Martin Peck