ASP.NETの設定ファイル(Web.config)の値を取得するサンプルです。
確認環境 ・Microsoft Visual Studio Community 2019 |
目次
設定ファイル | Web.configファイル |
サンプル | 設定ファイルへの値のセットと取得 |
Web.configファイル
- ファイルに任意のキーと値(value)を追記してそれをコードから取得できます。
- 場所は、プロジェクトの直下にあります。
設定ファイルへの値のセットと取得
1.設定ファイルに値をセットする
設定ファイル(Web.config)のappSettingsにkeyとvalueを追加します。
<appSettings>
<add key="test1" value="testです"/>
<add key="test2" value="赤,黄,青"/>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
2,3行目に新規で行を追加しました。
3行目は、値を3つセットしています。カンマで区切っています。
2.設定ファイルから値を取得する
上記で設定した値をコードで取得するサンプルです。
VB.NET版
Namespace Controllers
Public Class test1Controller
Inherits Controller
Function Index() As ActionResult
Dim str1 As String
str1 = ConfigurationManager.AppSettings("test1")
' 変数str1の値は「testです」
Dim str2() As String
str2 = ConfigurationManager.AppSettings("test2").Split(",")
'変数str2は配列で値は「赤」「黄」「青」
Return View()
End Function
End Class
End Namespace
8行目は、引数にappSettingsのkeyを指定し、そのkeyに対応するvalueを取得します。
12行目は、Splitメソッドで配列にしています。
以下は、C#版です。
using System;
using System.Configuration;
using System.Web.Mvc;
namespace csharp1.Controllers
{
public class test1Controller : Controller
{
public ActionResult Index()
{
string str1;
str1 = ConfigurationManager.AppSettings["test1"];
// 変数str1の値は「testです」
string[] str2;
str2 = ConfigurationManager.AppSettings["test2"].Split(',');
// 変数str2は配列で値は「赤」「黄」「青」
return View();
}
}
}
12行目は、keyを指定し、そのキーに対応するvalueを取得します。
16行目は、Splitメソッドで配列にしています。
以下は、MicrosoftのConfigurationManager.AppSettings プロパティのリンクです。
https://docs.microsoft.com/ja-jp/dotnet/api/system.configuration.configurationmanager.appsettings?view=netframework-4.8
関連の記事