1:appsettings.jsonファイル
{ " ロギング" :{ " ログレベル" :{ " デフォルト":" 警告" } }、 " AllowedHosts ":" * " 、 " のconnectionStrings " :{ " SqlServerConnection ":" データソース= 127.0.0.1;初期カタログ=試験;ユーザID = SA;パスワード= sa0123 " } }
2:クラスConfigurationHelperを作成します。
パブリック 静的 クラスConfigurationHelper { /// <要約> /// 读取JSON文件 /// </要約> /// <typeparam名= "T"> 类型</ typeparam> /// <PARAM NAME = "ParentKey "> 父级JSON节点</ PARAM> /// <PARAM NAME =" childrenKey "> 子级节点</ PARAM> /// <PARAM NAME ="パス"> appsettings.json </ PARAM> /// <リターン> </戻り> パブリック 静的 オブジェクト GetAppSettings <T>(文字列 parentKey、文字列 childrenKey = nullを、文字列パスは= " appsettings.json " ) { オブジェクト strInfo = ストリング.Empty。 VaRのビルダー= 新しいConfigurationBuilder()AddJsonFile(パス)。 VaRの構成= builder.Build()。 してみてください { 場合(!文字列.IsNullOrWhiteSpace(childrenKey)) { strInfo = configuration.GetSection(parentKey)以降.getvalue <T> (childrenKey)。 } 他 { strInfo = 構成[parentKey] .ToString(); } 戻りstrInfo。 } キャッチ(例外例) { // LogHelper.Error(ex.Message.ToString())。 リターン ヌル。 } } }
3:ノードを読んで呼び出し
(1)個々のノードAllowedHostsを読み取ります
VaRの STR = ConfigurationHelper.GetAppSettings < オブジェクト >(" AllowedHosts ")。
(2)次のSqlServerConnectionノードのConnectionStringを読み取ります
VaRの STR = ConfigurationHelper.GetAppSettings < オブジェクト >(" のconnectionStrings "、" SqlServerConnection ");
或者
VAR STR = ConfigurationHelper.GetAppSettings <オブジェクト>( "のconnectionStrings:SqlServerConnection")。