很多时候我们需要使用过滤器来实现一些拦截、验证等行为,此时我们能获取到的Context是ActionExecutingContext ,我们如何通过这个Context来获得Action、Controller等对象呢?记录下:
在代码中
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ViewLogAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); } }
更加简洁的办法:
var areaName = filterContext.ActionDescriptor.RouteValues["area"];
var controllerName = filterContext.ActionDescriptor.RouteValues["controller"];
var actionName = filterContext.ActionDescriptor.RouteValuse["action"];
1.获取控制器名称代码
MVC中
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
MVC Core中需强行转下
var controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor).ControllerName;
或者使用
filterContext.Controller.GetType().Name
MVC中还可以
var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"];
2.获取Action名称代码
var actionName = filterContext.ActionDescriptor.ActionName;
或
var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["Action"];
3.获取Action参数名称
//获取参数数组 var arrParameter = filterContext.ActionDescriptor.GetParameters(); //根据索引获取对应参数名 var paramName = arrParameter[0].ParameterName;
4.获取参数值
var parameterValue = filterContext.Controller.ValueProvider.GetValue(paramName).RawValue;
如果可以确定参数名称可以直接用ActionParameters通过Key来获取,Key指参数名称
var parameterValue = filterContext.ActionParameters["KeyName"];