Tono Nam
Tono Nam

Reputation: 36070

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.

Upvotes: 0

Views: 4217

Answers (2)

cezn
cezn

Reputation: 3055

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

Upvotes: 3

Tono Nam
Tono Nam

Reputation: 36070

Sorry I did not knew I could add a Configuration to an existing configuration. This is what I ended up doing to override the default appsettings.MyApp.json configuration file


var filePath = Path.Combine(AppContext.BaseDirectory, $"appsettings.{MyApp.InstanceId}.json");
if (File.Exists(filePath))
{
    var newConfigBuilder = new ConfigurationBuilder().AddJsonFile(filePath, optional: true, reloadOnChange: true);  
    builder.Configuration.AddConfiguration(newConfigBuilder.Build());
}

Now if that file exists my app will first try to read values from that file and if it does not exist it will then failover to appsettings.MyApp.json and if that file does not exist then it will failover to appsettings.json

Upvotes: 0

Related Questions