asp.net core读取appsettings.json,如何读取多环境开发配置

2022-11-18,,,,

摘要

读取appsettings.json文件中配置的时候,觉得最简单的方式就是使用asp.net core注入的方式进行读取了。

步骤

首先根据配置项的结构定义一个配置类,比如叫AppSettings的类。

然后在Startup中注册。

  public void ConfigureServices(IServiceCollection services)
{ services.AddMvc(); var appSettings = services.Configure<AppSettings>(Configuration.GetSection(Env_Section_Name)); }

然后在使用的控制器或者类中的构造函数进行注入,类似下面的代码

 public class OfficeBusiness
{ private AppSettings _appSettings;
public OfficeBusiness(
IOptions<AppSettings> appSettings,
)
{
_appSettings = appSettings.Value;
}
}

开发中,经常遇到多环境的开发环境(生成,测试,中国,美国),那么该如何进行配置更方便呢?可以设置如下的节点结构,以环境为父节点,具体环境配置为该节点的子节点。

在发布的时,修改Configuration.GetSection(Env_Section_Name)中的参数即可。

asp.net core读取appsettings.json,如何读取多环境开发配置的相关教程结束。

《asp.net core读取appsettings.json,如何读取多环境开发配置.doc》

下载本文的Word格式文档,以方便收藏与打印。