Using LINQ and Reflection: How to query for all Cl

2019-07-29 23:20发布

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?

2条回答
Emotional °昔
2楼-- · 2019-07-29 23:46

I think that a better way of accomplishing this is:

var controllerList = (from type in Assembly.GetExecutingAssembly().GetTypes()
                      where !type.IsAbstract
                      where type.IsSubclassOf(typeof(Controller)) || type.IsSubclassOf(typeof(System.Web.Http.ApiController))
                      where type.IsDefined(typeof(AuthorizeAttribute), allInherited)
                      select type).ToList();

Or if you're looking for any attribute that has "Authorize" in it:

var controllerList = from type in myAssembly.GetTypes()
                     where type.Name.Contains("Controller")
                     where !type.IsAbstract
                     let attrs = type.GetCustomAttributes(allInherited).OfType<Attribute>()
                     where attrs.Any(a => a.Name.Contains("Authorize"))
                     select type;
查看更多
仙女界的扛把子
3楼-- · 2019-07-30 00:07

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.

查看更多
登录 后发表回答