Asp .Net Core 读取appsettings.json配置文件
Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的。那么今天给大家介绍下具体如何读取配置文件的。 首先创建一个读取配置文件的公共类GetAppsetting,我们可以看下此时配置文件中的内容
{ "GetSetting": { "option1": "value1_from_json", "option2": -1, "subsection": { "suboption1": "subvalue1_from_json", "suboption2": 200 } }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
在创建的GetAppsetting公共类中写如下代码
/// <summary> /// 实例化、调用GetAppsetting() /// </summary> /// <param name="builder"></param> public static void connection(IConfiguration build) { getvalue = new GetAppsetting(build); } /// <summary> /// 在类中进行连接 /// </summary> public static GetAppsetting getvalue { get; private set; } /// <summary> /// 最终实例化GetAppsetting(配置文件),读取到GetSetting下面的配置 /// </summary> /// <param name="builder"></param> public GetAppsetting(IConfigurationbuild) { this.GetSettings = new GetSetting(build.GetSection("GetSetting")); } public GetSetting GetSettings { get; } /// <summary> /// 获取配置下面的具体属性的值 /// </summary> public class GetSetting { public string option1 { get; } public GetSetting(IConfiguration Configuration) { this.option1 = Configuration.GetSection("option1").Value; } }
最后需要在Program中的Main函数中初始化
var Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); GetAppsetting.connection(Configuration);
var a = GetAppsetting.getvalue.GetSettings.option1;//这样我们就可以拿到配置文件中GetSetting下面的option1的属性值了
参考:
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2
欢迎大家扫描下方二维码,和我一起学习更多的知识😊
原文地址:https://www.cnblogs.com/hulizhong/p/10692033.html
相关推荐
-
.NetCore&Linux&Docker&Portainer踩坑历险记 C#
2019-6-26
-
Unity技术博客 – 客户端断点续传 C#
2019-8-30
-
【C#进阶系列】27 I/O限制的异步操作 C#
2019-6-26
-
EF Core中避免贫血模型的三种行之有效的方法(翻译) C#
2019-7-23
-
你必须知道的EntityFramework 6.x和EntityFramework Core变更追踪状态 C#
2019-5-12
-
C#-Xamarin利用ZXing.Net.Mobile进行扫码 C#
2019-5-14
-
ASP.NET Core JWT 认证 C#
2019-8-29
-
扒一扒.NET Core的环境配置提供程序 C#
2019-5-23
-
如何在ASP.NET Core中自定义Azure Storage File Provider C#
2019-4-2
-
在Bootstrap开发框架中使用Grid++报表,实现在线预览PDF的几种解决方案 C#
2019-5-17