91

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

4

7 回答 7

114

您可以尝试ActionDescriptor以下方法ActionExecutingContext

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
   string actionName = filterContext.ActionDescriptor.ActionName;
   string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName
   .....
   base.OnActionExecuting(filterContext);
}
于 2013-08-30T14:26:42.283 回答
41

你可以ActionDescriptor使用ActionExecutingContext

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var descriptor = filterContext.ActionDescriptor;
    var actionName = descriptor.ActionName;
    var controllerName = descriptor.ControllerDescriptor.ControllerName;
    ......
    base.OnActionExecuting(filterContext);
}
于 2013-08-30T14:25:30.450 回答
26

你可以看看RouteData

    Request.RequestContext.RouteData.Values["Controller"];
    Request.RequestContext.RouteData.Values["Action"];
于 2013-08-30T14:27:01.283 回答
18

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

var controllerName = ((ControllerBase)filterContext.Controller)
   .ControllerContext.ActionDescriptor.ControllerName;
var actionName = ((ControllerBase)filterContext.Controller)
   .ControllerContext.ActionDescriptor.ActionName;
于 2019-08-06T03:57:05.457 回答
14

ActionExecutingContext 上下文这将是您的上下文....

var actionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName;
var controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ControllerName;
于 2017-10-09T10:32:54.687 回答
1
var controllerName = (string)routingValues["controller"];

var actionName = (string)routingValues["action"];
于 2016-02-06T06:21:57.750 回答
-1

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

  • 动作名称表单属性构造函数:

        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)

于 2021-01-07T17:53:58.990 回答