LoginSignup
2
1

More than 3 years have passed since last update.

.Net Core2.2でappsetting.jsonの値を使用するには

Posted at

環境

Tool Version
.Net Core 2.2

appsetting.json は以下とします。

appsetting.json
{
  "Sample": {
    "XXX": "XXX_Value"
  }
}

DI を利用

Startup.cs の ConfigureServices で appsetting.json のセクションを登録して置き、DI を利用して値を取得する方法です。

SampleConfig.cs
public class SampleConfig
{
 public string XXX { get; set; }
}
Startup.cs

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
    //....
    services.AddOptions().Configure<SampleConfig>(Configuration.GetSection("Sample"));
  }
}
SampleService.cs
public class SampleService
{
  private readonly IOptions<SampleConfig> _sampleConfig;

  public SampleService(IOptions<SampleConfig> sampleConfig)
  {
    _sampleConfig = sampleConfig;
  }

  public void SampleMethod()
  {
    string xxx = _sampleConfig.Value.XXX;
  }
}

コンストラクタで Value の値を入れてもいいかもしれません。

DI を利用しない

Startup.cs の ConfigureServices で値を利用したい場合は、DI を利用することはできません。

Configuration.GetValueを利用

この場合は値の単一取得になります。
:をつなげていくことで階層を指定して取得が可能です。

Startup.cs
public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
    //....
    string xxx = Configuration.GetValue<bool>("Sample:XXX");
    // or Configuration.GetSection("Sample").GetSection("XXX").Value;
    // or Configuration.GetSection("Sample:XXX").Value;
  }
}

Section の存在チェックがしたい場合は、Existsを使えばよいです。

if (Configuration.GetSection("Sample:XXX").Exists())
{
  // 存在した場合の処理
}

GetChildrenによる取得もありますが、GetSection で取れればいいのではないでしょうか。

Bind を利用

複数の値を取得したい場合はこちらのほうが良さそうです。

Startup.cs
public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
    //....
    var sampleConfig = new SampleConfig();
    Configuration.GetSection("Sample").Bind(sampleConfig);
  }
}

参考

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