WebAPI项目框架新建读取配置文件帮助类
在.netcore webapi 项目中,我们会把配置信息同意放置在appsettings.json中,通过新建读取帮助类,更加简单的读取配置信息。
新建公共类库文件夹Common,新建公共类库Web.Core.Common
在Web.Core.Common类库下新建Helper文件夹,新建AppSettings帮助类
.Net Core6.0 WebAPI项目框架搭建四:新建读取配置文件帮助类_List
.Net Core6.0 WebAPI项目框架搭建四:新建读取配置文件帮助类_json_02
在AppSettings.cs里面添加以下代码:
/// <summary>
/// appsettings.json操作类
/// </summary>
public class AppSettings
{
static IConfiguration Configuration { get; set; }
static string contentPath { get; set; }
public AppSettings(string contentPath)
{
string Path = "appsettings.json";
Configuration = new ConfigurationBuilder()
.SetBasePath(contentPath)
.Add(new JsonConfigurationSource
{
Path = Path,
Optional = false,
ReloadOnChange = true
}).Build();
}
public AppSettings(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 封装要操作的字符
/// </summary>
/// <param name="sections">节点配置</param>
/// <returns></returns>
public static string app(params string[] sections)
{
try
{
if (sections.Any())
{
return Configuration[string.Join(":", sections)];
}
}
catch (Exception)
{
}
return "";
}
/// <summary>
/// 递归获取配置信息数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <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;
}
}
对webapi添加项目引用
在program.cs里面添加服务
//注册appsettings读取类
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
在appsetting.json里面添加数据库连接字符串
在program.cs里面测试下AppSettings读取配置文件
运行项目显示配置文件内容: