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

蓝咒 提交于 2019-12-03 10:17:39

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

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;

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.

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

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

This works in .NET Core 1.0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!