1、 配置文件中修改
1)appsettings.json
在项目的appsettings.json文件中,可以为Kestrel配置监听的端口。
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:5400" }, "Https": { "Url": "https://localhost:5401" } } } }
2)launchSettings.json
出于开发目的修改,可以在launchSettings中更改。属性文件夹中的json文件:
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:22963", "sslPort": 44349 } }, "profiles": { "UrlTest": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://localhost:7244;http://localhost:5053", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
2、命令行参数
当使用dotnet run
启动项目时,可以通过命令行参数传递--urls
参数来指定URL:
dotnet run --urls "http://localhost:8000;https://localhost:8001"
3、环境变量
可以使用环境变量来设置监听的端口
1)在Windows上
set ASPNETCORE_URLS=http://0.0.0.0:1500;https://0.0.0.0:1501 dotnet run
2)在Linux或macOS上
export ASPNETCORE_URLS="http://localhost:2467;https://localhost:2468" dotnet run
4、Program.cs中的配置
可以在Program.cs中通过代码的方式修改:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run("http://localhost:6054");
或者
var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseUrls("http://localhost:3045"); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run();
参考文档:
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-6.0