ASP.NET Core – passing command-line arguments to Startup class

1. Introduction

I usually pass configuration to my web API via JSON files, but recently I needed to pass them also via command-line arguments. As the solution for ASP.NET Core 2.x is quite different than for ASP.NET Core 1.x I decided to describe both methods in here.

2. ASP.NET Core 2.x

For the newest version of ASP.NET Core, the solution is pretty straightforward as IConfiguration is injected by default to the Startup class. All we have to do is to add CommandLineConfigurationSource to IConfigurationBuilder when configuring IWebHost. CommandLineConfigurationSource is part of the Microsoft.Extensions.Configuration.CommandLine package and can be easily used by AddCommandLine extension method

Now we can access our command-line arguments just like any other configuration

3. ASP.NET Core 1.x

The solution for ASP.NET Core 1.x requires a bit more work but it is possible to achieve the same result. We still will be using CommandLineConfigurationSource from Microsoft.Extensions.Configuration.CommandLine package, however this time we have to manually create IConfiguration object and register it in the container before the Startup class is created. This is possible because the WebHostBuilder exposes ConfigureServices method.

Having our service registered now we can easily access IConfiguration object in our application


Source code for this post can be found here

ASP.NET Core – passing command-line arguments to Startup class

One thought on “ASP.NET Core – passing command-line arguments to Startup class

  1. Ruedi says: 

    Great post! Trying to start my app with IISExpress and later with IIS.
    Added -application to “Application arguments” in VS but it isn’t available in args.
    Any idea why?

Comments are closed.