如何在OnActionExecuting中获取控制器和动作名称?


78

是否可以找出OnActionExecuting中当前正在执行的控制器/动作?


9
如果这些答案中的任何一个解决了您的问题,则应考虑将其设为接受。
PickYourPoison

2
@loyalflow在这里说“嘿!听!请标记一个答案”,让我成为Navi
Dbl 2014年

Answers:


106

你可以尝试ActionDescriptorActionExecutingContext,如下所示:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
   string actionName = filterContext.ActionDescriptor.ActionName;
   string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName
   .....
   base.OnActionExecuting(filterContext);
}

38

您可以使用ActionDescriptorActionExecutingContext

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var descriptor = filterContext.ActionDescriptor;
    var actionName = descriptor.ActionName;
    var controllerName = descriptor.ControllerDescriptor.ControllerName;
    ......
    base.OnActionExecuting(filterContext);
}

我不好,这个不是针对网络核心的。
德里克

21

您可以看一下RouteData

    Request.RequestContext.RouteData.Values["Controller"];
    Request.RequestContext.RouteData.Values["Action"];

12

ActionExecutingContext上下文将成为您的上下文。

var actionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName;
var controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ControllerName;

1
该答案适用于.Net-Core
Derrick

9

对于ASP.NET Core,请使用以下命令,

var controllerName = ((ControllerBase)filterContext.Controller)
   .ControllerContext.ActionDescriptor.ControllerName;
var actionName = ((ControllerBase)filterContext.Controller)
   .ControllerContext.ActionDescriptor.ActionName;

该答案适用于.Net-Core
Derrick

1
var controllerName = (string)routingValues["controller"];

var actionName = (string)routingValues["action"];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.