我想得到我的ASP.NET Core
控制器的当前方法名
我尝试通过反射获得方法名称:
[HttpGet]
public async Task<IActionResult> CreateProcess(int catId)
{
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
但这给出了MoveNext
的值,而不是CreateProcess
的值。
注意我不想使用ViewContext
string methodName = ActionContext.RouteData.Values["action"].ToString();
由于我的urls是小写的,所以我通过上面的启动settings.The可以获得createprocess
而不是CreateProcess
。
我最好想要一个简单的一行,而不是多行扩展方法。
发布于 2016-02-21 01:41:18
您可以使用以下事实:它不仅仅是任何方法,而是一个控制器,并且可以使用ActionContext.ActionDescriptor.Name
属性来获取操作名。
最新消息:(感谢吉姆·阿霍)
最新版本适用于-
ControllerContext.ActionDescriptor.ActionName
发布于 2016-08-09 23:08:42
在ASP.NET核心中,它似乎已经改变了,您必须使用ActionName
属性
((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor).ActionName;
发布于 2016-02-21 01:51:52
C# 5.0 CallerMemberName属性可以完成此任务。(我还没有从异步方法中测试这一点;它是从常规调用中运行的)
private static string GetCallerMemberName([CallerMemberName]string name = "")
{
return name;
}
然后从代码中调用它:
[HttpGet]
public async Task<IActionResult> CreateProcess(int catId)
{
string methodName = GetCallerMemberName();
注意,您不需要将任何内容传递给该方法。
https://stackoverflow.com/questions/35534337
复制相似问题