当前位置: 代码迷 >> 综合 >> .NetCore AppSettings json配置文件读取
  详细解决方案

.NetCore AppSettings json配置文件读取

热度:64   发布时间:2023-12-01 12:41:37.0

使用步骤:

1.json 文件中添加config

{
    "Logging": {
    "LogLevel": {
    "Default": "Warning"}},"AllowedHosts": "*","Config": {
    "test": "Canon MG2500 series Printer"}
}

2.在Startup.cs的ConfigureServices中设置配置

AppSettingHelper.SetAppSetting(Configuration.GetSection("Config"));

3.读取 string str = AppSettingHelper.GetAppSetting(“test”);

AppSettingHelper帮助类代码:

/// <summary>
/// 读取appsetting配置
/// 0.json 文件中需要有Config ,"Config":{ "test": "zz" }
/// 1.在Startup.cs的ConfigureServices中设置配置 AppSettingHelper.SetAppSetting(Configuration.GetSection("Config"));
/// 2.读取 string connStr = AppSettingHelper.GetAppSetting("test");
/// ps:如果不存在Config下有test 会返回null
/// </summary>
public static class AppSettingHelper
{
    private static IConfigurationSection _configurationSection = null;/// <summary>/// 读取配置/// </summary>/// <param name="key"></param>/// <returns></returns>public static string GetAppSetting(string key){
    return _configurationSection.GetSection(key)?.Value;}/// <summary>/// 设置配置/// </summary>/// <param name="section"></param>public static void SetAppSetting(IConfigurationSection section){
    _configurationSection = section;}
}
  相关解决方案