ASP.NET Core 變更預設 port 的方式

優先度排序

變更 port 有許多方式,這裡先列出優先順序,優先順序由上至下為:
appsettings.json 的 Kestrel
程式內的 builder.WebHost.UseUrls
dotnet run --urls
appsettings.json 的 Urls
Properties/launchSettings.json 的 applicationUrl
環境變數 ASPNETCORE_URLS

程式內變更

    
var builder = WebApplication.CreateBuilder(args);
builder.WebHost
    .UseUrls("https://localhost:5001;http://localhost:5002");
    

執行時指定

    
dotnet run --urls=https://localhost:8080/
    

可以使用分號隔開來指定多個:
    
dotnet run --urls="http://localhost:8080/;https://localhost:8081/"
    

變更設定檔(appsettings.json)

修改專案下的 appsettings.json ,有兩種方式:

指定 Kestrel:
    
{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://localhost:5000"
      },
      "Https": {
        "Url": "https://localhost:5001"
      }
    }
  }
}
    

指定 Urls:
    
{
  "Urls":"http://localhost:8010/;https://localhost:8011/"
}
    

Kestrel 的優先度較高,如果兩個都有設定,會優先使用 Kestrel

變更設定文件(launchSettings.json)

修改專案下的 Properties/launchSettings.json
    
{
  "profiles": {
    "WebApplicationPortTest": {
      "applicationUrl": "https://localhost:7130;http://localhost:5297"
    }
  }
}
    

設定環境變數

在 windows 下設定環境變數是使用 $env
    
$env:ASPNETCORE_URLS="http://localhost:8002/;https://localhost:8003/"
    

留言