2010-06-10 74 views
1

目前,我试图确定我的程序集中的哪些“控制器”类具有使用Reflection和LINQ与它们关联的[Authorize]属性。使用LINQ和反射:如何在我的程序集中查询[Authorize]属性中的所有类?

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

此代码几乎可行。

如果我逐步跟踪LINQ语句,我可以看到当我“悬停”我在LINQ语句中定义的“attribs”范围变量填充了单个Attribute并且该属性碰巧属于AuthorizeAttribute类型。它看起来有点像这样:

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

显然,这条线在我的LINQ说法是错误的:

where attribs.Contains("Authorize") 

,我应该怎么写那里,而不是检测是否“attribs”包含AuthorizeAttribute类型或不?

回答

3

你会想这样做

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

你比较字符串这样的检查总是失败的对象,这应该工作。

+0

Riiiight。 “任何”方法。我知道“Contains”是错误的(因为Intellisense不允许我写Lambda表达式,但我无法弄清楚从列表中选择哪种方法...) - 谢谢,伙计。我知道这是一个简单的问题,有人可以立即指出。 – Pretzel 2010-06-10 17:04:39

+0

@Pretzel没问题 – luke 2010-06-10 17:08:39

0

我认为实现这个更好的方法是:

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

或者在它,如果你正在寻找有任何属性“授权”:

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; 
相关问题