⼆、读取appsettings.json配置
本⽂章基于VS2022  .Net6
.Net Core WebApi项⽬中我们将把配置⽂件统⼀放在appsettings.json⽂件中,我们将写⼀个读取配置⽂件的公⽤类。⼀、新建公共类库Common,⽤于存放⼀些公⽤⽅法
⼆、如上图:
使⽤Nuget安装
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.Binder
三、Common类库新建AppSetting.cs,代码如下
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace Common.Helper公司取名网
{
/// <summary>
/// appsettings.json操作类
/// </summary>读取配置文件失败
public class AppSetting
{
static IConfiguration Configuration { get; set; }
static string ContentPath { get; set; }
public AppSetting()
{
string path = "appsettings.json";
2015感动中国十大人物Configuration = new ConfigurationBuilder().SetBasePath(ContentPath).Add(new JsonConfigurationSource
{
Path = path,
Optional = false,
ReloadOnChange = true
}).Build();
}
public AppSetting(IConfiguration configuration)
{
Configuration = configuration;
周立波郭德纲对骂}
/// <summary>
/// 获取指定属性值
/// </summary>
/// <param name="sections"></param>
/// <returns></returns>
public static string app(params string[] sections)
{
try
try
{
if (sections.Any())
{
if (Configuration != null)
{
#pragma warning disable CS8603 // 可能返回 null 引⽤。
return Configuration[string.Join(":", sections)];
#pragma warning restore CS8603 // 可能返回 null 引⽤。
}
}
}
catch (Exception ex)
{
}
return "";
}
/// <summary>
/// 获取指定对象值
/// </summary>
/// <param name="sections"></param>
/
// <returns></returns>
public static List<T> app<T>(params string[] sections)
{
List<T> list = new List<T>();
Configuration.Bind(string.Join(":", sections), list);朱桦的歌
return list;
}
}
}
四、appsettings.json 内容如下
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
银赫iu"AppSettings": {
//数据库连接字符串
"ConnectionStrings": "Server=127.0.0.1;User Id=id;Password=pwd;Database=dbname;"
}
}
五、在项⽬ Program.cs ⾥使⽤ AddSingleton注册AppSetting,并测试读取AppSettings的ConnectionStrings,代码如下
//注册appsettings读取类
builder.Services.AddSingleton(new AppSetting(builder.Configuration));
//测试AppSetting操作
var text = AppSetting.app(new string[] { "AppSettings", "ConnectionStrings" });
Console.WriteLine($"ConnectionString:{text}");
Console.ReadLine();
六、运⾏测试结果如下