How to get the controller name and action name in MVC filter
Use the ActionExecutingContext object to get the controller name, action name, parameter name, and parameter value. Routes and Action return values do not affect the result.
in code
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ViewLogAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); } }
1. Get the controller name code
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
or
var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"];
2. Get Action name code
var actionName = filterContext.ActionDescriptor.ActionName;
or
var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["Action"];
3. Get the Action parameter name
//get parameter array var arrParameter = filterContext.ActionDescriptor.GetParameters(); //Get the corresponding parameter name according to the index var paramName = arrParameter[0].ParameterName;
4. Get the parameter value
var parameterValue = filterContext.Controller.ValueProvider.GetValue(paramName).RawValue;
If you can determine the parameter name, you can directly use ActionParameters to get it through Key, where Key refers to the parameter name
var parameterValue = filterContext.ActionParameters["KeyName"];
Source: https://www.cnblogs.com/paulhe/p/4138187.html
Use the ActionExecutingContext object to get the controller name, action name, parameter name, and parameter value. Routes and Action return values do not affect the result.
in code
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ViewLogAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); } }
1. Get the controller name code
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
or
var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"];
2. Get Action name code
var actionName = filterContext.ActionDescriptor.ActionName;
or
var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["Action"];
3. Get the Action parameter name
//get parameter array var arrParameter = filterContext.ActionDescriptor.GetParameters(); //Get the corresponding parameter name according to the index var paramName = arrParameter[0].ParameterName;
4. Get the parameter value
var parameterValue = filterContext.Controller.ValueProvider.GetValue(paramName).RawValue;
If you can determine the parameter name, you can directly use ActionParameters to get it through Key, where Key refers to the parameter name
var parameterValue = filterContext.ActionParameters["KeyName"];
Source: https://www.cnblogs.com/paulhe/p/4138187.html