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读取配置文件
运行项目显示配置文件内容:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构