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

时间:2013-08-30 14:22:40

标签: asp.net asp.net-mvc-4

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

7 个答案:

答案 0 :(得分:88)

您可以按以下方式尝试 ActionDescriptor ActionExecutingContext

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

答案 1 :(得分:33)

您可以使用ActionDescriptor

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

答案 2 :(得分:12)

您可以查看RouteData

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

答案 3 :(得分:5)

对于ASP.NET Core,请使用以下内容,

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

答案 4 :(得分:3)

ActionExecutingContext context 这将是您的背景....

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

答案 5 :(得分:2)

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

var actionName = (string)routingValues["action"];

答案 6 :(得分:-1)

我猜你使用属性(例如ActionFilterAttribute),如果是这样,你可以得到

  • action 命名表单属性构造函数:

        public CustomProfileAttribute([CallerMemberName]  string caller = null)
        {
            _actionName = caller;
        }
    
  • 控制器名称:

        public CustomProfileAttribute([CallerMemberName]  string caller = null)
        {
            _controllerName = context.Controller.ToString()
    
  • 控制器动作

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var controllerAndAction = context.ActionDescriptor.DisplayName;
    

    但在这种情况下,你会有一些丑陋的名字,比如 controller.action (action)