.NET6 读取appsettings.json
1、安装所有NuGet包
2、上代码
2.1 新建helper类
private static IConfiguration _config;
public AppsettingHelper(IConfiguration configuration)
{
_config = configuration;
}
/// <summary>
/// 读取appsettting.json文件
/// </summary>
/// <param name="key">待读取的配置文件中的key</param>
/// <param name="IsConn">是否读要取配置文件中的数据库链接串,默认false</param>
/// <returns>配置文件中key对应的value值,如果key空则返回NULL</returns>
public static string Get(string key, bool IsConn = false)
{
string value = null;
try
{
if (string.IsNullOrWhiteSpace(key))
{
return null;
}
//引用Microsoft.Extensions.Configuration;
var Configuration = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.test.json", true, reloadOnChange: true);
var config = Configuration.Build();
if (IsConn)
value = config.GetConnectionString(key);
else
value = config[key];
}
catch (Exception ex)
{
value = null;
}
return value;
}
/// <summary>
/// 读取实体信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <returns></returns>
public static List<T> Get<T>(params string[] session)
{
List<T> list = new List<T>();
_config.Bind(string.Join(":", session), list);
return list;
}
2.2 Program.cs注入服务
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
builder.Services.AddSingleton(new Y.WebAPI.Utility.AppsettingHelper(configuration));
2.3 定义配置文件节点类
public class RabbitMQConfig
{
public string HostName { set; get; }
public string Port { set; get; }
public string UserName { set; get; }
public string Password { set; get; }
public List<string> QueueName { set; get; }
}
2.4 使用
List<RabbitMQConfig> rabbitMQs = AppsettingHelper.Get<RabbitMQConfig>("RabbitMQ");
3、appsettings.json文件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"RabbitMQ": [
{
"HostName": "192.168.1.1",
"Port": "0000",
"UserName": "user1",
"Password": "111111",
"QueueName": [ "Y.Queue1"]
}
]
}