.net core mvc 类库读取配置文件
appsettings.json,给类库项目引入 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json程序包,类库中加载appsettings.json配置文件代码如下:
{ "ConnectionStrings": { "conn": "Server=localhost;port=3308;database=qdezge;uid=root;pwd=123456;" }, "AppSettings": { "AccessKey": "111111", "SecretKey": "22222", "Bucket": "3333333", "Domain": "http://wwww.domain.com" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "wmUrl": "https://www.baidu.com" }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using System; using System.Collections.Generic; using System.Text; namespace Infrastructure { /// <summary> /// 读取配置文件 /// </summary> public class AppConfigurtaionServices { public static IConfiguration Configuration { get; set; } static AppConfigurtaionServices() { //ReloadOnChange = true 当appsettings.json被修改时重新加载 Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); } } }
使用方法如下,读取数据库链接字符串
AppConfigurtaionServices.Configuration.GetConnectionString("conn"); //得Server=Server=192.168.10.254;port=3308;database=abc;uid=root;pwd=123456;
读取一级配置节点配置
AppConfigurtaionServices.Configuration["wmUrl"]; //得 https://www.baidu.com
读取二级子节点配置
AppConfigurtaionServices.Configuration["Appsettings:AccessKey"]; //得到 111111 AppConfigurtaionServices.Configuration["Appsettings:SecretKey"]; //得到 22222
注意,如果AppConfigurtaionServices类中抛出FileNotFoundException异常,说明目录下未找到appsettings.json文件,这时请在项目appsettings.json文件上右键——属性——将“复制到输出目录”项的值改为“始终复制”即可。