Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current ASP.NET core controller method name inside the controller using Reflection or another accurate method

Tags:

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

I have tried getting the method name through reflection:

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

but this gives me a value of MoveNext and not CreateProcess

Take note I don't want to use the ViewContext

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

as I lowercase my urls via the startup settings.The above will get me createprocess instead of CreateProcess

I preferably want an easy one-liner and not a multiline extension method.

like image 271
devfric Avatar asked Feb 21 '16 09:02

devfric


People also ask

How can we call controller method from view in asp net core?

You should not call a controller from the view. Add a property to your view model, set it in the controller, and use it in the view.


1 Answers

You can use the fact that it is not just any method but a controller and use ActionContext.ActionDescriptor.Name property to get the action name

UPDATE: (thanks to Jim Aho)

Recent versions work with -

ControllerContext.ActionDescriptor.ActionName 
like image 86
Felix Av Avatar answered Sep 24 '22 17:09

Felix Av