-1

I have an MVC4 app with multiple controllers that all inherit from BaseController. In some of these controllers, I have Actions with a Custom Attribute of PageKey. Page Key has two properties (Group & Key).

I need a way to get every instance of this attribute in all controllers and access the values. I also want to not have to modify the code later when I add new controllers or instances of the attribute.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Difinity
  • 235
  • 2
  • 12
  • Are you looking for: "find in files" as text OR some reflection code to get particular attribute on all classes/method in particular assembly OR something else? Please also comment on what do you means in "I want to not have to modify the code later" requirement. – Alexei Levenkov May 14 '14 at 22:17
  • This would be runtime code. I would like to find a way to either get all controllers in the application and cycle through them to find all instances of the attribute, or something similar and simpler. If I add a new controller or an new instance of the attribute at a later date, I don't want to have to add that controller name to a list to cycle through. It should just get it with the list of all controllers in the app. – Difinity May 14 '14 at 22:25
  • `Assembly.GetTypes`, than `Type.GetMethods` and [GetCustomAttributes](http://stackoverflow.com/questions/1268898/how-do-i-getcustomattributes). – Alexei Levenkov May 14 '14 at 23:29

1 Answers1

0

Ok, got it.

var attributes = Assembly.GetExecutingAssembly()
            .GetTypes()
            .SelectMany(t => t.GetMethods())
            .SelectMany(m => m.GetCustomAttributes())
            .Where(a => a.GetType() == typeof(PageKeyAttribute));

Thanks to Alexei Levenkov.

Difinity
  • 235
  • 2
  • 12