Problem
How to change the behaviour of your application for different environments.
Solution
Starting from an empty project, discussed in a previous post, modify the Configure()
method to use the IHostingEnvironment
to call different middleware based on the current environment:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
if (env.IsEnvironment("Development"))
Run(app, "Development");
else if (env.IsEnvironment("Staging"))
Run(app, "Staging");
else if (env.IsEnvironment("Production"))
Run(app, "Production");
else
Run(app, env.EnvironmentName);
}
IsEnvironment()
calls can be replaced with framework provided extension methods:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
if (env.IsDevelopment())
Run(app, "Development");
else if (env.IsStaging())
Run(app, "Staging");
else if (env.IsProduction())
Run(app, "Production");
else
Run(app, env.EnvironmentName);
}
There is also a Tag Helper provided by the framework to alter client-side behaviour:
<environment include="Development">
...
</environment>
Discussion
ASP.NET Core provides an interface IHostingEnvironment
to work with environments. Its IsEnvironment()
method can be used to verify the environment in use.
Framework also provides few extension methods (IsDevelopment, IsStaging, IsProduction
) to avoid developers hard-coding environment names. You could of course create your own extension methods for environments specific to your setup.
IHostingEnvironment
has few other useful properties that are set when WebHostBuilder
is configured in Program.cs:
ApplicationName
: Defaults to assembly name
ContentRootPath
: Path to folder where application assembly resides and from where MVC begins its search for content files like views
WebRootPath
: Path to the folder in your project for public
, static
resources like CSS, JavaScript, and image files
In order to set the environment your application is running in, you need to use environment variable ASPNETCORE_ENVIRONMENT
. This can be done in Visual Studio (for development use) from project Properties > Debug tab.
Usage
Application can change its behaviour depending on the Environment its running in. This can be useful in scenarios like:
- Configuring different middleware pipeline for development and production, e.g., using more detailed exception pages while developing
- Downloading different JavaScript and CSS files in views
- Reading different configuration files based on environment