Attribute.GetCustomAttributes() 没有得到我的自定义属性

Attribute.GetCustomAttributes() not getting my custom attribute

这是我的设置,我在解决方案上有三个项目: 项目 A:class MVC 库 项目B:MVC网站(主要) 项目 C:MVC 网站(仅限区域)

C 作为区域部署在 B 上,效果非常好。 B 引用了 A 和 C。C 引用了 A。

在 class 库 A 中,我定义了以下属性(删除了错误检查):

 [AttributeUsage(AttributeTargets.Method)]
 public class MyAttribute : Attribute {
     public string Name = "";
     public MyAttribute(string s)
     {
         Name = s;
     }
 }

然后在项目 C 中(与项目 B 中相同)我有一些 classes,其中一些方法用我的自定义属性修饰:

 public class SomeController : Controller, ISomethingSpecial
 {
      [MyAttribute("test")]
      public ActionResult Index() {
          return View();
      }
 }

自定义属性应用于属性使用约束所指示的操作方法。

为了测试,我把这段代码放在控制器的一个动作方法中:

IEnumerable<System.Type> all =
        System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<System.Reflection.Assembly>().SelectMany(a => a.GetTypes()).Where(type => typeof(ISomethingSpecial).IsAssignableFrom(type)).ToList();

foreach (Type t in all) {
    if (!t.Equals(typeof(ISomethingSpecial))) {
       MyAttribute[] sea = (MyAttribute[])Attribute.GetCustomAttributes(t, typeof(MyAttribute));
    }
}

当我调试代码时,我到达了检查类型 tSomeController 的迭代,它有一些用我的自定义装饰的方法属性。但是我看到返回的 GetCustomAttributes 列表有 zero 个元素!

在有人问我之前,我基本上想要实现的是获取实现 ISomethingSpecial 接口的 Web 应用程序的程序集列表,然后从候选列表中我想提取用我的自定义属性修饰的方法(MVC 操作方法)的名称 MyAttribute.

您的属性是在方法上定义的,而不是在 class 上定义的。但是在您的代码中,您从 class 请求自定义属性。如果您需要从方法中获取属性,您应该使用

遍历每个方法
Type.GetMethods

https://msdn.microsoft.com/en-us/library/4d848zkb(v=vs.110).aspx

并且对于每个方法请求自定义属性,就像您现在为您的 classes 所做的那样。