Pass command-line arguments to Startup class in ASP Core

BanksySan picture BanksySan · Jul 20, 2017 · Viewed 27.9k times · Source

I have arguments passed in via the command-line

private static int Main(string[] args)
{

    const string PORT = "12345"    ;

    var listeningUrl = $"http://localhost:{PORT}";

    var builder = new WebHostBuilder()
        .UseStartup<Startup>()
        .UseKestrel()
        .UseUrls(listeningUrl);

    var host = builder.Build();
    WriteLine($"Running on {PORT}");
    host.Run();

    return 0;
}

One of these arguments is a logging output directory. How do I get this value into my Startup class so I can write out to this directory when I receive a request?

I'd like to avoid using a static class. Would a service that supplies the value be the right way? If so, how do I get services injected into my middleware?

Answer

DavidG picture DavidG · Jul 20, 2017

You should be able to use the AddCommandLine() extension. First install the Nuget package Microsoft.Extensions.Configuration.CommandLine and ensure you have the correct import:

using Microsoft.Extensions.Configuration;

Now update your Main method to include the new config:

var config = new ConfigurationBuilder()
    .AddJsonFile("hosting.json", optional: true) //this is not needed, but could be useful
    .AddCommandLine(args)
    .Build();

var builder = new WebHostBuilder()
    .UseConfiguration(config)  //<-- Add this
    .UseStartup<Startup>()
    .UseKestrel()
    .UseUrls(listeningUrl);

Now you treat the command line options as configuration:

dotnet run /MySetting:SomeValue=123

And read in code:

var someValue = Configuration.GetValue<int>("MySetting:SomeValue");