ASP.NET Core 6(.NET 6) 修改默认端口的方法(5000和5001)

在ASP.NET Core 6 (.NET 6) 中,项目默认使用Kestrel作为其Web服务器,并监听5000(HTTP)和5001(HTTPS)端口。如想更改这些默认端口,有几种方法可以做到。本文主要介绍一下修改默认端口的方法。

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/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-6.0

推荐阅读
cjavapy编程之路首页