IHostEnvironment describes the running ASP.NET Core hosting environment. WebApplicationBuilder creates it from DOTNET_ENVIRONMENT or ASPNETCORE_ENVIRONMENT, with ASPNETCORE_ENVIRONMENT taking precedence. Its EnvironmentName commonly identifies Development, Staging, or Production, while ContentRootPath identifies the application directory used for files such as appsettings.json. Browser-facing static files belong under WebRootPath, exposed through IWebHostEnvironment. section 10.4.1
Use the environment to adapt startup behavior:
- Test environments with IsDevelopment(), IsStaging(), IsProduction(), or IsEnvironment(string); these checks are case-insensitive. section 10.4.1
- Load appsettings.EnvironmentName.json after appsettings.json so matching environment-specific keys override shared settings. section 10.4.2
- Add providers conditionally, such as User Secrets in development, and select different middleware for development versus staging or production. section 10.4.2
- Prefer strongly typed configuration settings in application services instead of injecting IHostEnvironment outside Program.cs. section 10.4.2
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
The listing demonstrates obtaining the current environment from WebApplicationBuilder and using EnvironmentName to select an optional configuration file. section 10.4.2
