EnvironmentName identifies the environment in which an ASP.NET Core application is running. Set through ASPNETCORE_ENVIRONMENT, it commonly uses Development, Staging, or Production. section 10.4.1
Use the hosting environment to vary application behavior:
- Check environments with IsDevelopment(), IsStaging(), IsProduction(), or IsEnvironment(string); these methods compare names case-insensitively. section 10.4.1
- Load an optional appsettings.{EnvironmentName}.json file after appsettings.json so environment-specific values override shared settings. section 10.4.2
- Include providers such as User Secrets only in Development, or select different middleware for development and deployed environments. section 10.4.2
Environment-specific configuration
Read the current environment from builder.Environment, then add appsettings.json followed by an optional file whose name includes env.EnvironmentName. A Development run can therefore load appsettings.Development.json after the shared settings.
Listing 10.13 Adding environment-specific appsettings.json files
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); IHostEnvironment env = builder.Environment; #1 builder.Configuration.Sources.Clear(); builder.Configuration .AddJsonFile( "appsettings.json", optional: false) #2 .AddJsonFile( #3 $”appsettings.{env.EnvironmentName}.json”, #3 Optional: true); #3 WebApplication app = builder.Build(); app.MapGet("/", () =>"Hello world!"); app.Run(); #1 The current IHostEnvironment is available on WebApplicationBuilder. #2 It’s common to make the base appsettings.json compulsory. #3 Adds an optional environment-specific JSON file where the filename varies with the environment
Inspect a runnable Program.cs example that builds environment-specific configuration with WebApplicationBuilder. section 10.4.2
