How to set ASPNETCORE_ENVIRONMENT variable at runtime

This is how I set EnvironmentName variable when publishing my application:

dotnet publish -c Release -r win-x64 /p:EnvironmentName=MyCustomValue

I got that from this link:

How to set ASPNETCORE_ENVIRONMENT to be considered for publishing an ASP.NET Core application

As a result my application will try to find settings values from:

appsettings.MyCustomValue.json file and if that file does not exist it will attempt to get it from appsettings.json.

Anyways I will like to change the value of EnvironmentName variable at runtime. The reason is because I only want to publish my application once and distribute it to multiple servers. It makes no sense to have to publish the same application multiple time each with a different EnvironmentName variable.

This is what I have tried doing

WebApplicationBuilder builder = WebApplication.CreateBuilder();
builder.WebHost.UseEnvironment(System.IO.File.ReadAllText(/path/to/some/file...));

But that does not work.


Solution 1:

You should configure your hosting environment (Azure/AWS/Container orchestrator/whatever) to set ASPNETCORE_ENVIRONMENT=YourCustomValue environment variable for the app. Each environment should provide different values. For instance, in AWS ECS you would do:

{
    "family": "",
    "containerDefinitions": [
        {
            "name": "app",
            "image": "app:latest",
            ...
            "environment": [
                {
                    "name": "ASPNETCORE_ENVIRONMENT",
                    "value": "YourCustomValue"
                }
            ],
            ...
        }
    ],
    ...
}

In docker-compose:

version: '3'
services:
  app:
    image: app:latest
    environment:
      - ASPNETCORE_ENVIRONMENT: 'YourCustomValue'

If you start it from a shell script:
ASPNETCORE_ENVIRONMENT=YourCustomValue dotnet App.dll