.NET Core独立部署:如何修改ASP.NET Core Web API的端口?
修改ASP.NET Core 6独立部署Web API的端口方法
下面是几种常用的修改端口的方式,按需选择:
1. 命令行临时指定端口
启动生成的EXE文件时,直接通过--urls参数指定端口,无需修改任何文件:
# 仅指定HTTP端口 YourApi.exe --urls "http://localhost:8080" # 同时指定HTTP和HTTPS端口 YourApi.exe --urls "http://localhost:8080;https://localhost:8081"
这种方式适合临时调整端口,重启后若不加参数会回到默认配置。
2. 修改appsettings.json配置文件
在项目的appsettings.json中添加Urls节点,配置目标端口,部署后每次启动都会生效:
{ "Urls": "http://localhost:8080;https://localhost:8081", "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
如果需要区分开发/生产环境,可以对应修改appsettings.Development.json或appsettings.Production.json。
3. 代码中固定端口配置
在Program.cs里通过ConfigureKestrel直接指定监听端口,这种方式属于硬编码,适合不需要灵活修改端口的场景:
var builder = WebApplication.CreateBuilder(args); // 配置Kestrel监听端口 builder.WebHost.ConfigureKestrel(serverOptions => { // 监听本地HTTP端口8080 serverOptions.ListenLocalhost(8080); // 监听本地HTTPS端口8081并启用HTTPS serverOptions.ListenLocalhost(8081, opts => opts.UseHttps()); }); // 注册服务、配置中间件... var app = builder.Build(); app.Run();
4. 通过环境变量指定
设置ASPNETCORE_URLS环境变量后再启动EXE,适合不同环境快速切换端口:
- Windows命令提示符:
set ASPNETCORE_URLS=http://localhost:8080;https://localhost:8081 YourApi.exe - Linux/macOS终端:
export ASPNETCORE_URLS="http://localhost:8080;https://localhost:8081" ./YourApi
内容的提问来源于stack exchange,提问作者Sam Carleton
相关产品推荐
相关产品推荐

