ASP.NET Core 2.0 Environments

Problem

How to change the behavior 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 current environment,

  1. public void Configure(  
  2.             IApplicationBuilder app,  
  3.             IHostingEnvironment env)  
  4.         {  
  5.             if (env.IsEnvironment("Development"))  
  6.                 Run(app, "Development");  
  7.             else if (env.IsEnvironment("Staging"))  
  8.                 Run(app, "Staging");  
  9.             else if (env.IsEnvironment("Production"))  
  10.                 Run(app, "Production");  
  11.             else  
  12.                 Run(app, env.EnvironmentName);  
  13.         } 

IsEnvironment() calls can be replaced with framework provided extension methods,

  1. public void Configure(  
  2.     IApplicationBuilder app,  
  3.     IHostingEnvironment env)  
  4. {  
  5.     if (env.IsDevelopment())  
  6.         Run(app, "Development");  
  7.     else if (env.IsStaging())  
  8.         Run(app, "Staging");  
  9.     else if (env.IsProduction())  
  10.         Run(app, "Production");  
  11.     else  
  12.         Run(app, env.EnvironmentName);  
  13. }  

There is also a Tag Helper provided by the framework to alter client-side behavior,

  1. <environment include="Development">  
  2.     ...  
  3. </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 a 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 behavior depending on Environment it’s 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.

Source Code

GitHub