简体   繁体   中英

Specifying Kestrel port with command line arg for .NET Core 3.1

Here's my Program.CS

public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    // Set properties and call methods on options
                })
                .UseKestrel()
                .UseIISIntegration()
                .UseStartup<Startup>();
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
                config.AddCommandLine(args);
            });
    }

I am running the app via the following command:

dotnet run --server.urls http://localhost:59708

However, the app will only listen on port 59707, not port 59708. I am trying to set the port with command line args so that I can run multiple instances of the app on separate static ports

Call .UseKestrel() like this:

.UseKestrel((ctx, opt) =>
{
    var ipAddress = IPAddress.Parse("127.0.0.1")
    var port = 80;
    opt.Listen(ipAddress, port);
    // for HTTPS
    //opt.Listen(ipAddress, httpsPort, listenOptions =>
    //{
    //    listenOptions.UseHttps("certificate.pfx", "password");
    //});
}

You can easily figure out how to parse your command line arguments . Options are almost endless...

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM