2016-01-26 30 views
1

這是我的設置,我有解決方案三個項目: 項目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裝飾。

回答

0

您的屬性定義在方法上,而不是類。但是在你的代碼中,你需要從你的類中請求定製屬性。如果你需要從方法的屬性,你應該使用

Type.GetMethods 

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

和喜歡你的課,現在做每一個方法請求自定義屬性遍歷每個方法。

+0

謝謝,只有一分鐘之前,但只有當我查看局部變量時,我發現我得到零是因爲該類沒有自定義屬性。無論如何,這確實是答案! –

相關問題