views:

80

answers:

1

Currently, I'm trying to identify which "Controller" classes in my assembly have the [Authorize] attribute associated with them using Reflection and LINQ.

const bool allInherited = true;
var myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var controllerList = from type in myAssembly.GetTypes()
                     where type.Name.Contains("Controller")
                     where !type.IsAbstract
                     let attribs = type.GetCustomAttributes(allInherited)
                     where attribs.Contains("Authorize")
                     select type;
controllerList.ToList();

This code almost works.

If I trace through the LINQ statement step-by-step, I can see that when I "mouseover" the "attribs" range variable that I define in the LINQ statement is populated with a single Attribute and that attribute happens to be of type AuthorizeAttribute. It looks sort of like this:

[-] attribs | {object[1]}
   [+]  [0] | {System.Web.Mvc.AuthorizeAttribute}

Clearly, this line in my LINQ statement is wrong:

where attribs.Contains("Authorize")

What should I write there instead to detect if "attribs" contains the AuthorizeAttribute type or not?

+3  A: 

you would want to do

attribs.Any(a => a.GetType().Equals(typeof(AuthorizeAttribute))

you were comparing an object with a string so the check was always failing, this should work.

luke
Riiiight. The "Any" method. I knew "Contains" was wrong (because Intellisense wasn't allowing me to write a Lambda expression, but I couldn't figure out which method to choose from the list...) -- Thanks, man. I knew it was a simple issue that someone would be able to point out immediately.
Pretzel
@Pretzel no problem
luke