This article will discuss how to customize the hosting environment in an ASP.NET Core application based on the environment in which it is deployed because the environment has an impact on how the application behaves.
When an ASP.NET Core application is running, the hosting environment in ASP.NET Core is used to specify which environment it is operating on (Development, Staging, or Production). The Hosting Environment in ASP.NET Core can be set to any single value and can take on various values for the same application running on various computers or servers. Development, Staging, and Production are the environments that the framework provides, but you can also specify your own settings, such as Testing, QA, PrePROD, etc.
The application can be customized according to the environment in which it is executing thanks to environment variables.
An application must go through many phases including Development, Testing, & Production as part of the software development life cycle. Different parameters must be configured by application developers for various environments. In other words, depending on the environment (Development, UAT, or Production) in which the application is running, each environment will have its own database (connection string, user id/password, etc.), different versions (URLs) of third-party services, and different settings for application features like logging, bundling, minification, exception handling, etc.
These parameters can be controlled at runtime by a variety of circumstances, including database connections, third-party service URLs, and application behavior like logging, exception handling, bundling, etc.
Configuring Your ASP.NET Core Hosting Environment
The ASP.NET Core hosting environment can be set up in a variety of ways. On each system where the application is needed to execute, this environment variable needs to be configured.
The following command can be used to set the environment variable from the command prompt. This is relevant to the current session, and the dotnet run command should be used to launch the application.
using windows command line
set ASPNETCORE_ENVIRONMENT=Staging dotnet run --no-launch-profile
using PowerShell
$Env:ASPNETCORE_ENVIRONMENT = "Staging" dotnet run --no-launch-profile
using windows environment variables
Use windows environment variables to specify the hosting environment in ASP.NET Core variables globally so that you don’t need to set them before executing the application.
Open Control Panel > System > Advanced System Settings > Environment Variables > System Variable to set an environment variable globally. Set values for “name” and “value” under New/Edit, then click “OK.”
using web.config
Environment variable can be set in web.config as well. Environment variable can be specified for the process in the processPath attribute in web.config. Environment variables set in this section takes precedence over system environment variables.
<aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess"> <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" /> </environmentVariables> </aspNetCore>
using Per IIS Application Pool
For an application operating in a separate application pool, environment variables can also be specified at the level of the IIS pool. A system setting is overridden when ASPNETCORE_ENVIRONMENT is set for an app pool.
<applicationPools> <add name="CorePool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic"> <environmentVariables> <add name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </add> </applicationPools>
AppCmd.exe can be used to add environment variables to the IIS pool level.
appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='CorePool'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging']" /commit:apphost
After setting the environment variable in IIS, restart IIS or Server so that the application can access the new values.
How to use hosting environment in ASP.NET Core in your application
The environment-based starting class example shown below uses IWebHostingEnvironment to determine the environment and apply code behavior appropriately.
public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); } //Remaining code was removed public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); //Remaining code was removed } }
The appsettings.json file will be used based on the environment defined for the application, i.e. appsettings.development.json or appsettings.production.json file, depending on the environment provided at runtime, in the code above’s starting constructor.
Additionally, dependent on the runtime environment, various application behavior for handling exceptions has been configured in the configure method.
How to add custom hosting environment in ASP.NET Core
The framework comes with development, staging, and production environments by default. But any string value can be provided for ASPNETCORE_ENVIRONMENT. You can add the following extension class to configure your own environments.
public static class HostingEnvironmentExtensions { public const string QAEnvironment = "QA"; public const string UATEnvironment = "UAT"; public const string TestEnvironment = "Test"; public static bool IsQA(this IWebHostEnvironment hostingEnvironment) { return hostingEnvironment.IsEnvironment(QAEnvironment); } public static bool IsUAT(this IWebHostEnvironment hostingEnvironment) { return hostingEnvironment.IsEnvironment(UATEnvironment); } public static bool IsTest(this IWebHostEnvironment hostingEnvironment) { return hostingEnvironment.IsEnvironment(TestEnvironment); } }
It will be accessible under the environment variable as indicated below once configured.
Summary
ASP.NET Core’s hosting environment gives developers flexibility over how their applications operate in various settings. The program can set an environment variable in a variety of ways.
By default, ASP.NET Core has 3 environments (development, staging, and production), however additional environments can be added, and the environment name can essentially be anything.