使用 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”范围变量时,会使用单个属性填充该变量,并且该属性恰好是 AuthorizeAttribute 类型。它看起来有点像这样:
[-] attribs | {object[1]}
[+] [0] | {System.Web.Mvc.AuthorizeAttribute}
显然,我的 LINQ 语句中的这一行是错误的:
where attribs.Contains("Authorize")
我应该在那里写什么来检测“attribs”是否包含 AuthorizeAttribute 类型?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要
将对象与字符串进行比较,因此检查总是失败,这应该可行。
you would want to do
you were comparing an object with a string so the check was always failing, this should work.
我认为实现此目的的更好方法是:
或者如果您正在寻找其中包含“授权”的任何属性:
I think that a better way of accomplishing this is:
Or if you're looking for any attribute that has "Authorize" in it: