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

または、「Authorize」を含む属性を探している場合:

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 に答える