//在应用程序的任何地方注入 IConfiguration 来访问配置数据。ASP.NET Core 默认会加载 appsettings.json 文件
IConfiguration _configuration = builder.Configuration;
string connectionString = _configuration["ConnectionStrings:SqlServerConnection"];
Helper帮助类
private static IConfigurationRoot Configuration { get; set; }
static ConfigurationTools()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
Configuration = builder.Build();
}
/// <summary>
/// 默认获取ConnectionStrings节点下配置
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetConnectionString(string name)
{
return Configuration.GetConnectionString(name);
}
/// <summary>
/// 将Key查询的数据自动封装成类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetAppSetting<T>(string key)
{
return Configuration.GetSection(key).Get<T>();
}