目前,我正在尝试使用反射和 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”范围变量填充了单个属性,并且该属性恰好是 AuthorizeAttribute 类型. 它看起来像这样:
[-] attribs | {object[1]}
[+] [0] | {System.Web.Mvc.AuthorizeAttribute}
显然,我的 LINQ 语句中的这一行是错误的:
where attribs.Contains("Authorize")
我应该在那里写什么来检测“attribs”是否包含 AuthorizeAttribute 类型?