一、在 .csproj 项目主文件中添加 EnvironmentName
可以在 .csproj 项目主文件中增加 <EnvironmentName> 节点来设置环境变量,在对应的编译平台加入此节点,对应相应的环境即可,重新编译时,会自动添加到web.config文件中。
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile></DocumentationFile>
<WarningLevel>5</WarningLevel>
<NoWarn>1701;1702;1591</NoWarn>
<FileAlignment>1024</FileAlignment>
<DebugType>portable</DebugType>
<DebugSymbols>true</DebugSymbols>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<DefineConstants>TRACE</DefineConstants>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
<DocumentationFile></DocumentationFile>
<OutputPath></OutputPath>
<NoWarn>1701;1702;1591</NoWarn>
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
二、在 FolderProfile.pubxml 中添加 EnvironmentName
在Properties => PublishProfiles,文件目录下,有.pubxml后缀的文件,这些文件用来发布的,此处可以添加不同的文件,用于区分开发环境和生产环境,如:Development.pubxml、Production.pubxml 在这两个文件中,加入EnvironmentName节点即可,如下:
Development.pubxml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
</Project>
Production.pubxml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
</Project>
以上文件有删减,直接复制节点即可,不可直接使用。
三、在使用dotnet publish 命令中添加
在用 dotnet pulish 发布项目时,可以在发布参数中指定 环境变量。
dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development
四、cmd配置
Command Line : setx ASPNETCORE_ENVIRONMENT "Development"
PowerShell : $Env:ASPNETCORE_ENVIRONMENT = "Development"
五、直接在发布后或者生成后的web.config文件中添加
environmentVariables
如下所示:
<?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="bin\Debug\net6.0\*.exe" arguments="" stdoutLogEnabled="false" hostingModel="InProcess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
</configuration>
直接复制 <environmentVariables>节点即可,不要全篇复制使用。