6
5

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.

.Net Coreでアプリケーション構成ファイルを使う

Posted at

ASP.NET Core WebアプリケーションにはデフォルトでWeb.configが存在しません。

今までのようにアプリケーションの構成要素をファイルに格納したい場合は、
次の2通りのやり方が存在します。

  1. appsettings.jsonを使う
  2. configファイルを新規追加する

1.appsettings.jsonを使う

appsettings.jsonに[AppSettings]Keyを追加します。

appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
    "AllowedHosts": "*",
    //新規追加
    "AppSettings": {
        "ApiEndPoint": "http;//hoge",
        "DefaultTimeOut_Minitue": "120"
    }
}

Startupクラスにappsettings.jsonに追加したAppsettingsを取得するDictionary型のプロパティを用意して、
ConfigureServicesメソッドで代入します。
(AppSettingsプロパティと取得処理はこのクラス以外でもかまいません。)

Startup.cs
public static Dictionary<string, string> AppSettings{get; private set;}

 public void ConfigureServices(IServiceCollection services)
{
    AppSettings = Configuration.GetSection("AppSettings").GetChildren().ToDictionary(x => x.Key, x => x.Value);
}

AppSettingsプロパティはStartUpクラスの静的メンバなので、後は使い箇所で使いまわしてください。

    var endPoint = Startup.AppSettings["ApiEndPoint"];

2.configファイルを新規追加する

プロジェクト右クリック>追加で構成ファイルを追加します。
名称はapp.configにしておきます。

image.png

app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="test" value="123"/>
  </appSettings>
</configuration>

ConfigurationManagerをNugetで取得します。
ツールバーの[ツール]>[NuGetパッケージマネージャー]>[パッケージマネージャーコンソール]で
パッケージマネージャーコンソールを開いたら、次のコマンドを実行します。
※既定のプロジェクトが、ConfigurationManagerを追加したいプロジェクトになっているか確認して下さい。

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

appSettingsの値を取得したいクラスにusingを追加したら、
ConfigurationManagerクラスを使って値を取得します。

using System.Configuration;

var app = ConfigurationManager.AppSettings["test"];
6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?