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,

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:

Source Code

GitHub