Most articles talk about setting the host environment in ASP.NET Core using Environment Variables, but I wanted to set the host environment in an ASP.NET Core Web Application using command line arguments. This is actually really easy to do.

Microsoft.Extensions.Configuration.CommandLine

There is a dependency you need to add to your ASP.NET Core Application, called Microsoft.Extensions.Configuration.CommandLine. This adds an extension method that reads command line arguments as configuration information. Therefore, in project.json, add Microsoft.Extensions.Configuration.CommandLine as a dependency.

"dependencies": {
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0"
}

ConfigurationBuilder.AddCommandLine(args)

When creating the host using WebHostBuilder, pass it a configuration source that includes command line arguments. First, create the configuration source using ConfigurationBuilder. Call the builder.AddCommandLine(args) extension method to populate the configuration with command line arguments. Note that this extension method is only available if you added Microsoft.Extensions.Configuration.CommandLine as a dependency.

var builder = new ConfigurationBuilder();
builder.AddCommandLine(args);
var config = builder.Build();

WebHostBuilder.UseConfiguration(config)

Tell WebHostBuilder to use this configuration information via its UseConfiguration method.

var host = new WebHostBuilder()
    .UseConfiguration(config)
    ...

Here is sample code in an ASP.NET Core Web Application.

using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace WebApp {
    public class Program {
        public static void Main(string[] args) {
            var builder = new ConfigurationBuilder();
            builder.AddCommandLine(args);
            var config = builder.Build();

            var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Set Host Environment Using Command Line Arguments

Pass the host environment as a command line argument when running the ASP.NET Core Web Application. You can pass it any string you want, but most of the time you will probably specify "Production", "Staging", or "Development" as the host environment for your ASP.NET Core Web Application.

dotnet run --environment "Staging"

Project webapp (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling webapp for .NETCoreApp,Version=v1.0

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

Time elapsed 00:00:01.8089388
 

Hosting environment: Staging
Content root path: /Users/Sasquatch/Core/webapp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Using EnvironmentName in ASP.NET Core Startup

You can use the host environment to help configure your ASP.NET Core Web Appication during startup. For example, it is common to load specific appsettings per environment that can add to or replace default settings using env.EnvironmentName.

public class Startup {
    public Startup(IHostingEnvironment env) {

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // ...

It is also common to use the methods IsDevelopment(), IsStaging(), and IsProduction() on IHostEnvironment when configuring an ASP.NET Core Web Application.

public class Startup {
    public Startup(IHostingEnvironment env) {

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsDevelopment()) {
            builder.AddUserSecrets();
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // ...

Conclusion

Often the tools, whether it be Visual Studio, Visual Studio Code, or JetBrains Rider, pass the host environment when debugging or starting the application, but sometimes you need to do this yourself. I find the easiest way to set the host environment is via command line arguments as opposed to environment variables or other means.

I hope this helps!

You can reach me on twitter as @KoderDojo.

Posted by Koder Dojo

Welcome to KoderDojo. I am a freelance, C# ASP.NET MVC Developer currently learning ASP.NET Core as well as Python, computer science, algorithms, and data science. I write articles almost daily about new things I have learned and hope they inspire and help other developers. If you find the website useful, please follow me on twitter so I know these articles make a difference. I would love to meet other people passionate about learning. I am on twitter as @KoderDojo. Best Wishes!

Related Posts: