

指定 ASP.NET Core 应用监听的端口
source link: https://beginor.github.io/2020/08/06/specify-the-port-of-asp-net-core-application.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

指定 ASP.NET Core 应用监听的端口
ASP.NET Core 应用默认监听的端口是 5000 , 在调试或者部署的过程中经常需要指定监听的端口来来运行, 本文就这个问题, 进行一个总结, 可以通过下面的方法来指定运行端口。
使用命令行参数
使用命令行参数 --urls
是最常用的方法了, 测试或者开发环境下用的最多。 只需要在运行命令中添加这个参数即可, 如下所示:
dotnet run --urls=http://localhost:5001/
在 appsettings.json
中添加配置
如果倾向于使用配置文件, 可以在 appsettings.json
文件中添加 urls
节点, 如下所示:
{
"urls": "http://localhost:5001"
}
这样, 执行 dotnet run
时, 会自动读取这个配置。
ASP.NET Core 应用在启动时会自动读取名称以 ASPNETCORE
开头的环境变量, 所以也可以通过环境变量来指定监听的端口。
export ASPNETCORE_URLS=http://localhost:5001/
dotnet run
在微软提供的
mcr.microsoft.com/dotnet/core/aspnet
Docker 镜像中, 就是用这个环境变量来指定监听端口的。
使用 UseUrls()
函数
如果倾向于使用代码, 则可以在 Program.cs
文件中的 ConfigureWebHostDefaults
方法中使用 UseUrls()
函数, 在代码中指定要监听的端口:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(builder => {
builder.UseStartup<Startup>();
builder.UseUrls("http://localhost:5001/");
});
在实际的项目中, 可以将要监听的端口配置到其它地方, 而不必硬编码在代码中过。
使用 Kestrel 服务器选项
ASP.NET Core 内置的 kestrel 服务器, 也提供了许多选项, 当然也包括了要监听的端口, 要在应用中使用 Kestrel 服务器选项, 需要在 Program.cs
文件中的 CreateHostBuilder
方法中添加 ConfigureServices
方法, 对 KestrelServerOptions
进行配置, 代码如下:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) => {
services.Configure<KestrelServerOptions>(
context.Configuration.GetSection("kestrel")
);
})
.ConfigureWebHostDefaults(builder =>{
builder.UseStartup<Startup>();
});
也可以在
Startup.cs
文件中的ConfigureServices
方法中进行配置。
然后在 appsettings.json
中添加 kestrel
节点, 内容如下所示:
{
"kestrel": {
"endPoints": {
"http": {
"url": "http://localhost:5001/"
}
}
}
}
KestrelServerOptions
还提供了许多额外的配置选项, 比如最大并发连接数、是否返回服务器名称标头等, 具体可以参考 kestrel-aspnetcore-3.1 , 如果需要同时调整额外的服务器配置, 则推荐使用这种方式。
Recommend
-
2
V2EX › Windows wsl2 手动监听一个端口,但发现打开的却不是这个端口请问是为什么 ysn2233...
-
10
招数学习 Ubuntu 开放指定端口 2021-05-27 一般情况下,ubuntu安装好的时候,iptables会被安...
-
11
centos学习 ssh 远程登陆指定端口 2021-05-30 ssh 到指定端口 ssh -p xx user@...
-
7
指定 ASP.NET Core Kestrel 接聽 Port-黑暗執行緒分享 ASP.NET Core 菜烏問題一枚。 使用 Visual Studio 或 dotnet 命令列工具編譯發佈 ASP.NET Core 專案後,執行 dotnet WebAsmName.dll 可啟動 Kestrel 執行網站,預設是聽 httq://localhost:5000 及 h...
-
8
比较常见的命令有:netstatlsofps/proc/$pidnetstat# netstat -tuapn参数解释:
-
10
监听端口到底是什么意思? ...
-
8
V2EX › Linux win 下 tcp 监听 localhost8000 端口, wsl 内的 ubuntu 如何与之连接? raw0xff
-
5
监听端口是计算机当前正在使用的端口,用于建立计算机之间的网络连接。虽然打开、监...
-
5
在对应用模型的基本构建方式具有大致的了解之后,我们来系统地认识一下描述应用模型的ApplicationModel类型。对于一个描述MVC应用模型的ApplicationModel对象来说,它承载...
-
6
ASP.NET Core MVC应用模型的构建[1]: 应用的蓝图 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK