3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dot net core アプリケーションでapplication.jsonを参照する

Posted at

結論

application.jsonの記述に対応したclassを作成し、Startup.csと使用するコントローラで読み込み処理を記述する。

環境

JetBrains Rider
dot net core 2.2
C#

準備

appication.json

  "IsDebug": false,
  "Logging": {
    "LogLevel": "Warning"
    }
  },

対応クラス(AppSetting.cs)

    public class AppSetting
    {
        public bool IsDebug { get; set; }

        public Logging Logging { get; set; }        
    }

読み込み用クラス(Logging.cs)

    public class Logging
    {
        public string LogLevel { get; set; }
    }

読み込み

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            // 元からある行
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            
            // これを追記
            services.Configure<AppSetting>(Configuration);
        }

HogeController.cs

        public HogeController(IOptions<AppSettings> optionsAccessor)
        {
            AppSetting = optionsAccessor.Value;
        }

        private AppSetting AppSetting { get; }

これでコントローラ内で値が設定されたAppSettingクラスを参照できます。
オブジェクトもキャストしてくれるみたいで便利。

3
1
1

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?