如何使用反射或其他准确方法获取控制器内部的当前ASP.NET核心控制器方法名称 [英] How to get the current ASP.NET core controller method name inside the controller using Reflection or another accurate method
问题描述
我想获取我的ASP.NET Core
控制器的当前方法名称
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;
但这给我的值为MoveNext
而不是CreateProcess
but this gives me a value of MoveNext
and not CreateProcess
请注意,我不想使用ViewContext
Take note I don't want to use the ViewContext
string methodName = ActionContext.RouteData.Values["action"].ToString();
当我通过启动设置小写我的网址时,上面的代码将使我成为createprocess
而不是CreateProcess
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.
推荐答案
您可以使用以下事实:它不仅是任何方法,而且是控制器,并可以使用ActionContext.ActionDescriptor.Name
属性获取操作名称
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
更新:(感谢Jim Aho)
UPDATE: (thanks to Jim Aho)
最新版本适用于-
ControllerContext.ActionDescriptor.ActionName
这篇关于如何使用反射或其他准确方法获取控制器内部的当前ASP.NET核心控制器方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!