23

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.

6 Answers 6

26

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

3 Comments

@JimAho what version of asp .net you're using?
@JimAho and you get an error or exception? I've checked and successfully used it
I can't even write that bit of code without getting a compilation error. ActionContext is a class and not a propery when trying to access it inside an action.
14

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

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

Comments

4

The C# 5.0 CallerMemberName attribute may do the trick. (I haven't tested this from an async 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 don't need to pass anything to the method.

1 Comment

7-1/2 years later and this solution still works great. The cleanest and easiest.
0

Use the StackTrace class snd its GetFrames until you find the one you want.

Comments

0

You can get it by base.ControllerContext.ActionDescriptor.ActionName

This works in .NET Core 1.0.

Comments

0

modifying dfmetro above solutions works for me

((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor).ControllerName; 

use .ControllerName to get the controller name.

not enough reputation to comment that's why i make i post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.