【发布时间】: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));
}
}
当我调试代码时,我进入了迭代,其中检查的类型 t 是 SomeController,它有一些用我的自定义属性修饰的方法。但是我看到返回的 GetCustomAttributes 列表有 zero 个元素!
在有人问我基本上想要实现的是获取实现 ISomethingSpecial 接口的 Web 应用程序的程序集列表之前,我想从候选列表中提取方法的名称(用我的自定义属性 MyAttribute 装饰的 MVC 操作方法。
【问题讨论】:
标签: asp.net-mvc linq reflection custom-attributes