Pass command-line arguments to Startup class in ASP Core

江枫思渺然 提交于 2019-12-01 03:12:29

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");

Dotnet Core 2

You don't have 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 Startip.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

ASP.NET Core 2 answer:

Change the default Program.cs to be:

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

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                config.AddEnvironmentVariables();
                config.AddCommandLine(args);
            })
            .UseStartup<Startup>()
            .Build();
}

I removed other bits just to make the configuration explanation easier.

Note the .AddCommandLine(args) line in the configuration builder.

Unlike @BanksySan's answer you DON'T need to create a static property, instead let DI inject the IConfiguration into the startup class.

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

    private IConfiguration Configuration { get; }

You can now use the configuration entries from any of the config providers, file, env variables and commandline.

Example:

dotnet run --seed true

    public void Configure(IApplicationBuilder app)
    {
        app.UseExceptionHandler("/Home/Error");

        var seed = Configuration.GetValue<bool>("seed");
        if (seed)
            SeedData.Initialize(app);

        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }

Hope this helps someone further.

DavidG's answer is correct, but there were still some pieces of the puzzle missing for me.

There are two Nuget packages you need:

  1. Microsoft.Extensions.Configuration.Binder
  2. Microsoft.Extensions.Configuration.CommandLine

Because we want the command line arguments, we need to create the configuration in the Main(string[]).

using Microsoft.Extensions.Configuration;

class Program
{
    private static int Main(string[] args)
    {
        const string PORT = "12345";

        var listeningUrl = $"http://localhost:{PORT}";
        var configuration = new ConfigurationBuilder()
                            .AddCommandLine(args)
                            .Build();
        // Set the `static` `Configuration` property on the `Startup` class.
        Startup.Configuration = configuration;

        var builder = new WebHostBuilder()
            .UseStartup<Startup>()
            .UseKestrel()
            .UseSetting("Message", "Hello World")
            .UseUrls(listeningUrl);

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

        return SUCCESS_EXIT_CODE;
    }
}

The Startup class is:

using Microsoft.Extensions.Configuration;

public class Startup
{
    public static IConfiguration Configuration { get; set; }


    public void Configure(IApplicationBuilder app)
    {
        foreach (var c in Configuration.AsEnumerable())
            Console.WriteLine($"{c.Key,-15}:{c.Value}");
    }
}

Is the command argument are --port 6000 outputDirectory C:\Temp then this will output:

port            :6000
outputDirectory :C:\Temp
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!