How to get the current name of an ASP.NET controller method inside a controller using Reflection or another exact method

I want to get the current method name of my ASP.NET Core controller

I tried to get the method name through reflection:

  [HttpGet] public async Task<IActionResult> CreateProcess(int catId) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; 

but it gives me the value of MoveNext , not CreateProcess

Please note: I do not want to use ViewContext

 string methodName = ActionContext.RouteData.Values["action"].ToString(); 

as I am building my urls using startup settings. The above text will get CreateProcess instead of CreateProcess

I prefer a simple single-line rather than multi-line extension method.

+6
source share
5 answers

You can use the fact that this is not only a method, but also a controller and use the ActionContext.ActionDescriptor.Name property to get the name of the action

UPDATE: (thanks Jim Aho)

Latest versions work with -

 ControllerContext.ActionDescriptor.ActionName 
+9
source

In ASP.NET Core, it seems to have changed, and you should use the ActionName property

 ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor).ActionName; 
+4
source

The C # 5.0 attribute CallerMemberName can do the trick. (I did not test this using the asynchronous operation method, it works from a regular call)

 private static string GetCallerMemberName([CallerMemberName]string name = "") { return name; } 

Then call it from your code:

 [HttpGet] public async Task<IActionResult> CreateProcess(int catId) { string methodName = GetCallerMemberName(); 

Note that you do not need to pass anything to the method.

+2
source

Use the StackTrace class for your GetFrames until you find the one you need.

0
source

You can get it base.ControllerContext.ActionDescriptor.ActionName

This works in .NET Core 1.0.

0
source

All Articles