您的位置:首页 > 移动开发

.NET Core读取配置文件appsettings.json

2020-07-28 09:31 71 查看

**

.NET Core读取配置文件
appsettings.json

**
前言
看过我前几篇博客的都知道,之前匆匆忙忙搭了一个.NET Core的框架,有很多小细节没有时间琢磨,比如配置文件我用的依然是

Web.config
,今天得了空咱就把他改成
appsettings.json
,盘它

appsettings.json
文件如下

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Config": {
"Host": "http://localhost:63657/",
"Environment": "Debug"
},

"AllowedHosts": "*"
}

比如我们要读取

Host
Environment
两个Config,要是放在
Web.config
里,加个
key
value
就好了,像这样

<appSettings>
<add key="Environment"  value="Debug"/>
</appSettings>

但在

appsettings.json
配置文件里,我们有其他读取方式,这里举例我用到的这一种。
1,配置一个类和配置文件结构相同,像这样

public class Config
{
public string Environment { get; set; }
public string Host { get; set; }
}

2,写一个读取配置文件的工具类,像这样

namespace Topwin.Astrazeneca.AZEView.Management.DBContext
{
/// <summary>
/// 读取配置文件
/// </summary>
public class ConfigServices
{
public static IConfiguration Configuration { get; set; }
static ConfigServices()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载
//生产发布path: appsettings.Production.jsonConfiguration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
}
}
}

3,读取配置文件,像这样

if (ConfigServices.Configuration.GetSection("Config").Get<Config>().Environment == "Prod"){ }

4,如果发生产,我们可以加一套配置文件,像这样

appsettings.Production.json

我们在步骤2中改一下要解析的配置文件名字即可,这样我们每次发布和本地调试只需要改一处这里就好了。

仅供学习参考,如有侵权联系我删除

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐