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

后端 未结 5 1554
深忆病人
深忆病人 2021-02-12 17:40

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

I have tried getting the method name through reflection:

    [HttpGet]
         


        
相关标签:
5条回答
  • 2021-02-12 17:59

    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.

    0 讨论(0)
  • 2021-02-12 18:01

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

    0 讨论(0)
  • 2021-02-12 18:19

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

    This works in .NET Core 1.0.

    0 讨论(0)
  • 2021-02-12 18:20

    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
    
    0 讨论(0)
  • 2021-02-12 18:22

    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;
    
    0 讨论(0)
提交回复
热议问题