mardi 26 janvier 2016

Attribute.GetCustomAttributes() not getting my custom attribute

This is my setup, I have three projects on the solution: Project A : class library for MVC Project B : MVC website (main) Project C : MVC website (area only)

C is deployed on B as an Area and that work really well. B has a reference to both A and C. C has a reference to A.

In class library A I defined the following attribute (error checking removed):

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

Then in project C (same as in project B) I have some classes where SOME methods are decorated with my custom attribute:

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

The custom attribute is applied to the action methods as indicated by the attribute usage constraint.

For the sake of testing I put this code in one of the action methods of the controller:

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));
    }
}

When I debug the code I get to the iteration where the examined type t is SomeController which has some methods decorated with my custom attribute. But I see that the returned list of GetCustomAttributes has zero elements!

Before somebody asks what I basically want to achieve is obtain a list of assemblies of the web application that implement the ISomethingSpecial interface and from that list of candidates I want to extract the names of the methods (MVC action methods) that are decorated with my custom attribute MyAttribute.





Aucun commentaire:

Enregistrer un commentaire