ASP.NET Action Filter无法获取自定义属性,求问题排查解决方法
问题分析与解决方案
我帮你找出了两处关键问题,咱们一步步来解决:
1. 自定义属性的构造函数访问权限错误
你的MyCustomAttribute构造函数没有指定访问修饰符,在C#中类的成员默认是**私有(private)**的,这意味着你根本无法在外部实例化这个属性(正常编译都会报错,更别说标记到Action方法上了)。
修正方法:把构造函数改成**公开(public)**的:
[AttributeUsage(AttributeTargets.Method, Inherited = true)] public sealed class MyCustomAttribute : Attribute { // 改为public构造函数,才能在外部实例化该属性 public MyCustomAttribute(string param) { } }
2. Action Filter中获取自定义属性的方式错误
你尝试从context.Filters里找自定义属性是方向错了——Filters集合存储的是应用到Action的过滤器实例,而不是咱们定义的自定义特性。正确的做法是从ControllerActionDescriptor中获取当前Action方法的元数据,再从中提取自定义属性。
修正后的OnActionExecuting方法代码:
public void OnActionExecuting(ActionExecutingContext context) { // 先将ActionDescriptor转换为ControllerActionDescriptor,拿到当前Action的方法信息 if (context.ActionDescriptor is ControllerActionDescriptor actionDescriptor) { // 从方法元数据中获取自定义属性 var myAttribute = actionDescriptor.MethodInfo.GetCustomAttribute<MyCustomAttribute>(); if (myAttribute != null) { // 这里就可以正常使用你的自定义属性了 // 比如如果给属性加了公开的参数字段,就能拿到传入的"test123" } } }
另外补充个小细节:如果需要在Filter里拿到你传入的"test123"参数,记得给自定义属性加个公开的存储字段:
[AttributeUsage(AttributeTargets.Method, Inherited = true)] public sealed class MyCustomAttribute : Attribute { // 公开存储构造函数传入的参数 public string Param { get; } public MyCustomAttribute(string param) { Param = param; } }
这样在Filter里就能通过myAttribute.Param拿到你传入的参数值了。
内容的提问来源于stack exchange,提问作者user911
相关产品推荐
相关产品推荐

