使用LINQ与反思:如何查询与[授权]属性在我的大会的所有类? [英] Using LINQ and Reflection: How to query for all Classes with [Authorize] Attribute in my Assembly?

查看:195
本文介绍了使用LINQ与反思:如何查询与[授权]属性在我的大会的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我试图找出我的组件,其控制器类与他们使用反射和LINQ相关的[授权]属性。

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();

这code几乎工作。

如果我通过LINQ声明一步一步的跟踪,我可以看到,当我鼠标悬停中的attribs范围,我在LINQ语句定义变量填充了一个单一的属性和属性恰好是类型AuthorizeAttribute。它看起来有点像这样的:

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}

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

Clearly, this line in my LINQ statement is wrong:

where attribs.Contains("Authorize")

我应该写了,而不是检测是否attribs包含AuthorizeAttribute类型或没有?

What should I write there instead to detect if "attribs" contains the AuthorizeAttribute type or not?

推荐答案

您会想这样做。

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

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

you were comparing an object with a string so the check was always failing, this should work.

这篇关于使用LINQ与反思:如何查询与[授权]属性在我的大会的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆