這是我的設置,我有解決方案三個項目: 項目A:類庫MVC 項目B:MVC網站(主) 項目C:MVC網站(區域只)Attribute.GetCustomAttributes()沒有得到我的自定義屬性
C部署在B作爲一個區域,並且工作得很好。 B具有指A的參考和C. C具有到A.
參考在類庫AI定義的下列屬性(檢查刪除錯誤):
[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));
}
}
當我調試的代碼,我得到的迭代,其中檢驗類型噸是SomeController其中有一些用我的自定義屬性裝飾的方法的。但我看到返回的GetCustomAttributes列表有零元素!
在有人問我基本上想要達到的目標是獲得實現接口的web應用程序的程序集列表,並從該候選列表中提取方法名稱(MVC操作方法)用我的自定義屬性MyAttribute裝飾。
謝謝,只有一分鐘之前,但只有當我查看局部變量時,我發現我得到零是因爲該類沒有自定義屬性。無論如何,這確實是答案! –