.NET Core 多环境

ASP.NET Core在应用启动时读取环境变量ASPNETCORE_ENVIRONMENT,ASPNETCORE_ENVIRONMENT可以设置任意值,但框架仅支持三个值:Development、Staging 和 Production,因此我们先在项目中添加appsettings.Development.json、appsettings.Production.json和appsettings.Staging.json以备用。

项目默认生成的appsettings.json用来存放公共配置,当我们设置Development环境时,最终的配置项是appsettings.Development.json和appsettings.json求并集的结果,若两文件有同名配置项则以appsettings.Development.json为准,其他环境同理。

 

1、开发时的环境变量

ASPNETCORE_ENVIRONMENT设置为Development,那在VS中调试的时候就会读取appsettings.Development.json的数据

ASPNETCORE_ENVIRONMENT设置为Production,那在VS中调试的时候就会读取appsettings.Production.json的数据 

ASPNETCORE_ENVIRONMENT设置为Staging,那在VS中调试的时候就会读取appsettings.Staging.json的数据 

 

2、发布后的环境变量

无论 ASPNETCORE_ENVIRONMENT设置为Development、Staging、Production,只要项目中有appsettings.Production.json,那项目发布后运行时默认会读取Production的配置。

无论 ASPNETCORE_ENVIRONMENT设置为Development、Staging、Production,只要项目中没有appsettings.Production.json,那项目发布后运行时就会仅读取appsettings.json的配置。

 

3、若想在发布后动态设置环境变量,可以通过修改web.config的方式来实现,Core项目中默认是没有web.config文件的,但是发布后会生成一个web.config文件,

我们可以通过添加<environmentVariable >节点来设置环境变量,如下图:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\Admin.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" >
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
        </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
</configuration>

注意: environmentVariables标签放在<aspNetCore> </aspNetCore>之间 

 

posted @ 2022-04-02 21:30  一夜秋2014  Views(214)  Comments(0Edit  收藏  举报