.NET Core在类库中读取配置文件appsettings.json
程序员文章站
2024-01-04 15:50:22
...
直接上代码,appsettings.json文件内容如下:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"CxyOrder": "Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;"
},
"Appsettings": {
"SystemName": "PDF .NET CORE",
"Date": "2017-07-23",
"Author": "PDF"
},
"ServiceUrl": "https://www.baidu.com/getnews"
}
建一个项目名称为Common的类库项目,并给该类库项目引入 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json程序包,类库中加载appsettings.json配置文件代码如下:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace Common
{
/// <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();
}
}
}
读取配置文件的代码完成了,只要引用了NetCoreOrder.Common类库的项目中都能方便读取数据库链接字符串和其他配置,使用方法如下:
AppConfigurtaionServices.Configuration.GetConnectionString("CxyOrder");
//得到 Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;
读取一级配置节点配置
AppConfigurtaionServices.Configuration["ServiceUrl"];
//得到 https://www.baidu.com/getnews
读取二级子节点配置
AppConfigurtaionServices.Configuration["Appsettings:SystemName"];
//得到 PDF .NET CORE
AppConfigurtaionServices.Configuration["Appsettings:Author"];
//得到 PDF
注意,如果AppConfigurtaionServices类中抛出FileNotFoundException异常,说明目录下未找到appsettings.json文件,这时请在项目appsettings.json文件上右键——属性——将“复制到输出目录”项的值改为“始终复制”即可。
推荐阅读
-
.NET Core在类库中读取配置文件appsettings.json
-
jenkins 读取json文件_干货:.net core实现读取appsettings.json配置文件(建议收藏)...
-
.net core读取配置文件appsettings.json
-
.NET Core读取配置文件appsettings.json
-
.NET Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
asp.net core 读取Appsettings.json 配置文件
-
ASP.NET在底层类库中获取Session C#类中获取Session 原创
-
ASP.NET在底层类库中获取Session C#类中获取Session 原创