使用LINQ与反思:如何查询与[授权]属性在我的所有装配类?(Using LINQ and Refl

2019-10-23 02:29发布

目前,我试图找出我的组件,其“控制器”类别与他们使用反射和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();

此代码几乎工作。

如果我通过LINQ语句一步一步追溯,我可以看到,当I“鼠标悬停”该“attribs”范围我在LINQ语句限定可变填充了一个单属性和属性恰好是类型的AuthorizeAttribute 。 它看起来有点像这样:

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

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

where attribs.Contains("Authorize")

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

Answer 1:

你会想这样做

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

你用一个字符串比较的对象,以便检查总是失败,这应该工作。



Answer 2:

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

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;


文章来源: Using LINQ and Reflection: How to query for all Classes with [Authorize] Attribute in my Assembly?