首页 资讯 > 正文

C# 读取json配置文件appsettings.json

2023-08-04 14:29:56 来源:博客园


(资料图片)

添加NuGet包

Microsoft.Extensions.Configuration.FileExtensions;

Microsoft.Extensions.Configuration.Json;

appsettings.json示例

代码:

public static void GetBuilder(string path){            var builder = new ConfigurationBuilder()                               //设置文件放置路径                               .SetBasePath(path)                               //appsettings.json,复制一份放在程序集目录下                               .AddJsonFile(appsettings, optional: true, reloadOnChange: true);           var configuration = builder.Build();           var connectionStr = configuration.GetConnectionString("Default")!;//数据库默认字符串的独特方式获取           var num = int.Parse(configuration.GetSection("Log:LogLevel").Value!);//方式一,通过":"来表示层级获取数据           var str = configuration.GetSection("Log").GetSection("LogPath").Value!;//方式二,直接通过叠加使用GetSection()来表示层级获取数据
}

完整示例

public static class AppConfigurations{        private const string appsettings = "appsettings.json";        public static readonly ConcurrentDictionary ConfigurationCache;        public static string ConnectionString { get; set; }            public static string LogPath{ get; set; }        public static int LogLevel{ get; set; }        static AppConfigurations()        {            ConfigurationCache = new ConcurrentDictionary();            ConnectionString = Get(Directory.GetCurrentDirectory()).GetConnectionString("Default")!;      LogLevel= int.Parse(Get(Directory.GetCurrentDirectory()).GetSection("Log:LogLevel").Value!);LogPath= Get(Directory.GetCurrentDirectory()).GetSection("Log").GetSection("LogPath").Value!;
}        public static IConfigurationRoot Get(string path)         {            var cacheKey = path;            return ConfigurationCache.GetOrAdd(                cacheKey,                _ => GetBuilder(path)            );        }        public static IConfigurationRoot GetBuilder(string path)        {            var builder = new ConfigurationBuilder()                               //设置文件放置路径                               .SetBasePath(path)                               //appsettings.json,复制一份放在程序集目录下                               .AddJsonFile(appsettings, optional: true, reloadOnChange: true);            return builder.Build();        }    }

注:运行时始终读不到配置抛出异常

原因是:配置文件没有复制成功到程序集目录下,没有成功的原因是配置文件的属性"复制到输出目录"值是不复制,此属性的值应改为,始终复制或者如果较新则复制,此处选择的是如果较新则复制(源文件有更新则重新复制)

关键词:

责任编辑:宋璟

返回首页
相关新闻
返回顶部