.net core 读取appsettings 的配置
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "CxyOrder": "Server=***;Database=***;User ID=***;Password=***;Trusted_Connection=False;" }, "Appsettings": { "SystemName": "PDF .NET CORE", "Date": "2017-07-23", "Author": "PDF" }, "ServiceUrl": "https://www.baidu.com/getnews" }
调用的方法 appsettings.json
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; namespace NetCoreOrder.Common { /// <summary> /// 读取配置文件 /// </summary> public class AppConfigurtaionServices { public static IConfiguration Configuration { get; set; } static AppConfigurtaionServices() { //ReloadOnChange = true 当appsettings.json被修改时重新加载 Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); } } }
读取一级配置节点配置
AppConfigurtaionServices.Configuration["ServiceUrl"]; //得到 https://www.baidu.com/getnews
读取二级子节点配置
AppConfigurtaionServices.Configuration["Appsettings:SystemName"]; //得到 PDF .NET CORE AppConfigurtaionServices.Configuration["Appsettings:Author"]; //得到 PDF
最后你执行的时候八成会遇到这个错误
The type initializer for '***' threw an exception.
这时候你需要
右键appsettings.json>>>属性》》》输出到目录改为始终复制
不复制的话读不到这个文件
仅仅为了做个笔记
转自:
https://www.cnblogs.com/pudefu/p/7580722.html
https://www.cnblogs.com/likui-bookHouse/p/11281074.html
还有其他的写法:
https://blog.csdn.net/weixin_34309435/article/details/86028477