Feature Image

Set ASPNETCORE_ENVIRONMENT in web.config using .NET Core CLI

Set ASPNETCORE_ENVIRONMENT in web.config using .NET Core CLI

In an ideal world, your lovely ASP Core application would be hosted in its own container in a sandboxed environment and separating Environmental Variables for different apps would be trivial. In the real world things are sometimes a bit muddier.

Problem:

Allow multiple ASP.NET Core apps to run in IIS on the same server but each have their own ASPNETCORE_ENVIRONMENT value that is generated via a CI pipeline.

Solution:

Pass the EnvironmentName parameter into the dotnet publish command. This will generate a web.config file for the application and include the ASPNETCORE_ENVIRONMENT property.

dotnet publish --configuration Release /p:EnvironmentName=Staging

The generated web.config file will look something similar to this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    ...
      
    <aspNetCore ...>
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

If you already have a web.config in the root of your web app for other things (adding/removing certain headers), then this will edit that file rather than replace it.

Azure Devops Pipeline

If you're looking to do this within an AzDO Yaml Pipeline, here's a sample of the code required:

  - task: DotNetCoreCLI@2
    displayName: 'Publish Web Project'
    inputs:
      command: publish
      publishWebProjects: True
      arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory) /p:EnvironmentName=Staging'
      zipAfterPublish: true

Sample

You can find a Hosted Blazor WebAssembly sample over at my GitHub