如何在 OnActionExecting 中获得控制器和操作名称?

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

62388 次浏览

You can use ActionDescriptor of ActionExecutingContext

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

You could try the ActionDescriptor of the ActionExecutingContext as follows:

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

You could look at the RouteData:

    Request.RequestContext.RouteData.Values["Controller"];
Request.RequestContext.RouteData.Values["Action"];
var controllerName = (string)routingValues["controller"];


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

ActionExecutingContext context this is going to be your context....

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

For ASP.NET Core, Use the following,

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

I guess you use Attributes (e.g. ActionFilterAttribute), if it so, you can get

  • action name form attribute constructor:

        public CustomProfileAttribute([CallerMemberName]  string caller = null)
    {
    _actionName = caller;
    }
    
  • controller name:

        public CustomProfileAttribute([CallerMemberName]  string caller = null)
    {
    _controllerName = context.Controller.ToString()
    
  • or both controller and action:

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

    but in such case you will have som ugly name like controller.action (action)