2017-03-16 19 views
6

.NETコアstartup.csの強く型付けされたオブジェクトにappsettings.jsonセクションを読み込むことに慣れています。たとえば:.NETコアの辞書にappsetting.jsonセクションを読み込む方法は?

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." 
} 

はコントローラにMobileConfigInfoを注入するIOptionsパターンを使用し、次いでMobileConfigInfo辞書オブジェクトにこのデータをロードしてする方法はありますか?

+0

がうーんASP.NETについて本当にこの質問をイマイチありません.NETコアではなく、コアですか?誤解を招くタイトルのビット。 – nashwan

答えて

9

あなたはstartup.csクラスに

Configuration.Bind(settings);を使用することができますし、設定クラスが

public class AppSettings 
{ 
    public Dictionary<string, string> MobileConfigInfo 
    { 
     get; 
     set; 
    } 
} 

ようになりますが、それがお役に立てば幸い! 辞書に変換したい他の人のために

3

appsettings.json内部のサンプルセクション

"MailSettings": { 
    "Server": "http://mail.mydomain.com"   
    "Port": "25", 
    "From": "[email protected]" 
} 

コードは、スタートアップファイル内に配置する必要があります後> ConfigureServices方法:

public static Dictionary<string, object> MailSettings { get; private set; } 

public void ConfigureServices(IServiceCollection services) 
{ 
    //ConfigureServices code...... 

    MailSettings = 
     Configuration.GetSection("MailSettings").GetChildren() 
     .Select(item => new KeyValuePair<string, string>(item.Key, item.Value)) 
     .ToDictionary(x => x.Key, x => x.Value); 
} 

これで、辞書f ROMのどこかのように:

string mailServer = Startup.MailSettings["Server"]; 

一つの欠点は、あなたが値はnullになります他のタイプをしようとした場合、すべての値は、文字列として取得されることです。

3

このような構造形式で行く:

"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); 
}); 
関連する問題