ASP.NET Core 2.0 Environments

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 current environment:

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

There is also a Tag Helper provided by the framework to alter client-side behaviour:

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 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: https://github.com/TahirNaushad/Fiver.Asp.Environment

Leave a Reply