ASP Net Core程序自定义IP和端口的几种方式

缺省ASP .Net Core Web API程序启动IP和端口是http://localhost:5000,我们可以通过以下几种方式修改和定制IP和端口。

1. 代码里设置端口

UseUrls函数可以设置IP和端口,而且还可以同时设置多个,程序会监听多个端口。

public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5555", "http://*:5556")
                .UseStartup()
                .Build();

2. 端口作为dotnet命令的参数

通过执行者执行动态传入端口参数,代码要做一些改动,最主要的是增加AddCommandLine(args):

public static IWebHost BuildWebHost(string[] args)
{
    var config = new ConfigurationBuilder()
    .AddCommandLine(args)
    .Build();
    return WebHost.CreateDefaultBuilder(args).UseConfiguration(config)
        .UseStartup()
        .Build();
}   

执行的时候增加参数:

$dotnet .\CustomPortSample.dll --server.urls "http://*:5001"
Hosting environment: Production
Content root path: D:\test\CustomPortSample\bin\Debug\netcoreapp2.0\publish
Now listening on: http://[::]:5001

3. 在appsettings.json里添加设置

代码也有点调整

public static IWebHost BuildWebHost(string[] args)
{
    var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .Build();
    return WebHost.CreateDefaultBuilder(args).UseConfiguration(config)
        .UseStartup()
        .Build();
}

另外在appsettings.json里添加节点:

{
  "server.urls": "http://localhost:4440;http://localhost:4442;",
}

运行的结果如下:

$dotnet .\CustomPortSample.dll
Hosting environment: Production
Content root path: D:\temp\CustomPortSample\bin\Debug\netcoreapp2.0\publish
Now listening on: http://localhost:4440
Now listening on: http://localhost:4442
Application started. Press Ctrl+C to shut down.

你可能感兴趣的:(ASP Net Core程序自定义IP和端口的几种方式)