【问题标题】:Attribute.GetCustomAttributes() not getting my custom attributeAttribute.GetCustomAttributes() 没有得到我的自定义属性
【发布时间】:2016-05-03 16:11:58
【问题描述】:

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

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

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

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

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

 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 应用程序的程序集列表之前,我想从候选列表中提取方法的名称(用我的自定义属性 MyAttribute 装饰的 MVC 操作方法。

【问题讨论】:

    标签: asp.net-mvc linq reflection custom-attributes


    【解决方案1】:

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

    遍历每个方法
    Type.GetMethods
    

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

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

    【讨论】:

    • 谢谢,我在一分钟前发现了那部分,但只有当我查看局部变量时,我才注意到我的值为零,因为该类没有自定义属性。无论如何,这确实是答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2013-01-25
    • 2010-11-13
    相关资源
    最近更新 更多