LoginSignup
4
3

More than 5 years have passed since last update.

ASP.NET Coreアプリで起動時にControllerの型情報一覧を取得する

Posted at

やること

ASP.NET Core Web Applicationで、起動時にコントローラーの一覧を取得します。

環境

  • Visual Strudio 2015
  • .NET Core Tooling Preview 2 for Visual Studio 2015

手順

IApplicationBuilderから以下のような感じで一覧のTypeInfoを取得できます。

public static void EnumControllers(IApplicationBuilder app)
{
    var manager = app.ApplicationServices.GetRequiredService<ApplicationPartManager>();

    var feature = new ControllerFeature();
    manager.PopulateFeature(feature);

    foreach (var typeInfo in feature.Controllers)
    {
        System.Diagnostics.Debug.WriteLine(typeInfo.AsType());
    }
}

HomeController、ValuesControllerの2つのコントローラーがあったとして、出力結果としては以下のような感じになります。

WebApplication1.Controllers.HomeController
WebApplication1.Controllers.ValuesController

うさコメ

起動時に、コントローラーのメタデータからなにかを構築したり、DIコンテナに明示的に情報を登録したり、みたいなことをしたい時用に(・ω・)

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3