使用LINQ和反射:如何在我的程序集中查询具有[Authorize]属性的所有类?
目前,我正在尝试使用反射和LINQ识别程序集中哪些“控制器”类具有与之相关联的[Authorize]属性使用LINQ和反射:如何在我的程序集中查询具有[Authorize]属性的所有类?,linq,reflection,attributes,authorize-attribute,Linq,Reflection,Attributes,Authorize Attribute,目前,我正在尝试使用反射和LINQ识别程序集中哪些“控制器”类具有与之相关联的[Authorize]属性 const bool allInherited = true; var myAssembly = System.Reflection.Assembly.GetExecutingAssembly(); var controllerList = from type in myAssembly.GetTypes() where type.Name.Cont
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语句,我可以看到当我“mouseover”时,我在LINQ语句中定义的“attribs”范围变量填充了单个属性,而该属性恰好是AuthorizeAttribute类型。看起来有点像这样:
[-] attribs | {object[1]}
[+] [0] | {System.Web.Mvc.AuthorizeAttribute}
显然,我的LINQ声明中的这一行是错误的:
where attribs.Contains("Authorize")
我应该在那里写些什么来检测“attribs”是否包含AuthorizeAttribute类型 你想做什么
attribs.Any(a => a.GetType().Equals(typeof(AuthorizeAttribute))
您将一个对象与一个字符串进行比较,因此检查总是失败,这应该是可行的。我认为更好的方法是:
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();
或者,如果您正在查找任何包含“Authorize”的属性:
var controllerList=来自myAssembly.GetTypes()中的类型
其中type.Name.Contains(“控制器”)
哪里类型.IsAbstract
设attrs=type.GetCustomAttributes(allInherited).OfType()
其中attrs.Any(a=>a.Name.Contains(“Authorize”))
选择类型;
riilight。“任何”方法。我知道“Contains”是错误的(因为Intellisense不允许我编写Lambda表达式,但我无法从列表中选择哪种方法…)——谢谢,伙计。我知道这是一个很简单的问题,有人会马上指出。
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;