1

目前,我正在尝试使用反射和 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 类型?

4

2 回答 2

3

你想做

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

您正在将对象与字符串进行比较,因此检查总是失败,这应该可以。

于 2010-06-10T16:54:27.363 回答
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;
于 2013-11-21T23:58:46.697 回答