MVC + EFCore 完整教程19-- 最简方法读取json配置:自定义configuration读取配置文件
问题引出
ASP.NET Core 默认将 Web.config移除了,将配置文件统一放在了 xxx.json 格式的文件中。
有Web.config时,我们需要读到配置文件时,一般是这样的:
var value1= ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
这个ConfigurationManager是在System.Configuration 命名空间下的。
很不幸,默认情况下这个方法也不能用了。
如果在Controller需要读取配置文件,在Startup.cs文件中注册相关服务,可以类似于注册context一样:
// 1、注册相关服务,类似于如下的XXXContext的例子 services.AddDbContext<XXXContext>(XXX 。。。 // 2、controller读取 然后在具体controller的构造函数中作为参数获取。 类似于: private IConfiguration _configuration; public XXXController(IConfiguration configuration) { _configuration = configuration; }
具体实现方式已有多篇文章讲解,请自行搜索,不再赘述。
这种方式引出两个问题:
1、多数controller是需要读取context的,但不是每个controller都需要读取配置文件,这种方式不够简洁
2、如果我们需要在controller之外的其他类文件中读取呢?
我们仿照ConfigurationManager读取Web.config中文件的方式,自定义一个MyConfigurationManager 类。
我直接在上一篇文章中的示例程序添加演示。
详细步骤
步骤一:准备好素材,appsettings.json添加配置项
"GrandParent_Key": { "Parent_Key": { "Child_Key": "value1" } },
"Parent_Key": { "Child_Key": "value2" },
"Child_Key": "value3"
步骤二:添加 MyConfigurationManager.cs
/// <summary> /// 获取自定义的 json 配置文件 /// </summary> static class MyConfigurationManager { public static IConfiguration AppSetting { get; } static MyConfigurationManager() { // 注意:2.2版本的这个路径不对 会输出 xxx/IIS Express...类似这种路径, // 等3.0再看有没其他变化 string directory = Directory.GetCurrentDirectory(); AppSetting = new ConfigurationBuilder() .SetBasePath(directory) .AddJsonFile("myAppSettings.json") .Build(); } }
步骤三:调用
我们去HomeController中添加一个测试方法
public IActionResult ConfigTest() { string value1 = MyConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"]; string value2 = MyConfigurationManager.AppSetting["Parent_Key:Child_Key"]; string value3 = MyConfigurationManager.AppSetting["Child_Key"]; return View(); }
加个断点调试一下,可以看到输出了想要的结果。
总结
通过自定义的Configuration方法可以方便读取json文件。
获取配置文件路径时,AppContext.BaseDirectory在 .net core 2.2和2.1不一样,
如果事先用的2.2模板,需要右键项目,将target framework设为2.1
P.S. 路径获取这块给出一个通用的方法,这样2.1和2.2就都满足了,如下:
var fileName = "appsettings.json"; var directory = AppContext.BaseDirectory; directory = directory.Replace("\\", "/"); var filePath = $"{directory}/{fileName}"; if (!File.Exists(filePath)) { var length = directory.IndexOf("/bin"); filePath = $"{directory.Substring(0, length)}/{fileName}"; }
祝 学习进步 :)
P.S. 系列文章列表:https://www.cnblogs.com/miro/p/3777960.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?