Pass command-line arguments to Startup class in ASP.NET Core

Viewed 46974

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?

5 Answers

Dotnet Core 2

You don't need most of the code as in dotnet core 1.0 to achieve this. AddCommandLinearguments are automatically injected when you BuildWebHost using the following syntax

Step 1.

public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
                  .UseStartup<Startup>()
                  .Build();
}

Step 2. Inject configurations to Startup.cs using DI using the following code

public class Startup
{
    private readonly IConfiguration Configuration;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    ...

}

Step 3. Access your arguments using configurations object.

var seed = Configuration.GetValue<bool>("seed");
Console.WriteLine($"seed: {seed}");

Step 4. Start application with arguments

dotnet run seed=True

If you just need the raw command line arguments passed to the process, or you don't want to add them to the configuration, you can still use the following:

Environment.GetCommandLineArgs();
Related