私は、appsettings.json セクションを .NET Core の厳密に型指定されたオブジェクトに読み込むことに慣れていますStartup.cs
。例:
public class CustomSection
{
public int A {get;set;}
public int B {get;set;}
}
//In Startup.cs
services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));
//Inject an IOptions instance
public HomeController(IOptions<CustomSection> options)
{
var settings = options.Value;
}
appsettings.json セクションには、時間の経過とともにキー/値のペアの数と名前が変化するものがあります。したがって、新しいキー/値のペアにはクラスのコード変更が必要になるため、クラスにプロパティ名をハードコードすることは現実的ではありません。キー/値のペアの小さなサンプルを以下に示します。
"MobileConfigInfo": {
"appointment-confirmed": "We've booked your appointment. See you soon!",
"appointments-book": "New Appointment",
"appointments-null": "We could not locate any upcoming appointments for you.",
"availability-null": "Sorry, there are no available times on this date. Please try another."
}
Dictionary<string, string>
このデータを MobileConfigInfoオブジェクトに読み込み、IOptions
パターンを使用して MobileConfigInfo をコントローラーに挿入する方法はありますか?
ベストアンサー1
次の構造形式を使用します。
"MobileConfigInfo": {
"Values": {
"appointment-confirmed": "We've booked your appointment. See you soon!",
"appointments-book": "New Appointment",
"appointments-null": "We could not locate any upcoming appointments for you.",
"availability-null": "Sorry, there are no available times on this date. Please try another."
}
}
設定クラスを次のようにします。
public class CustomSection
{
public Dictionary<string, string> Values {get;set;}
}
ではこれをやってください
services.Configure<CustomSection>((settings) =>
{
Configuration.GetSection("MobileConfigInfo").Bind(settings);
});