ASP.NET Core MVC如何在Filter中获取ControllerName和ActionName,以及在Action方法上声明的Filter
在ASP.NET Core MVC的Filter中,我们可以通过ActionContext对象获取到许多有用的信息,例如下面的代码在IAuthorizationFilter中,获取了ControllerName和ActionName,以及在Action方法上声明的Filter:
using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; namespace AspNetCoreMVCFilterDescriptor.Filters { public class AuthorizationFilterAttribute : Attribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { ControllerActionDescriptor? controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; string? controllerName = controllerActionDescriptor?.ControllerName;//获取ControllerName string? actionName = controllerActionDescriptor?.ActionName;//获取ActionName //获取在Action方法上声明的Filter IList<FilterDescriptor>? filters = controllerActionDescriptor?.FilterDescriptors; foreach (var filterDescriptor in filters!) { Type filterType = filterDescriptor.Filter.GetType(); } } } }
甚至我们还可以获取声明Filter的Controller的Action方法参数值,详情查看这里。