Kestrel服务器
Kestrel 服务器是什么
Kestrel 这个词的意思是红隼(小猛禽). 之前的 ASP.NET 应用深度绑定IIS服务, 跨平台和部署都是问题, 现在的 ASP.NET core 应用默认使用了 Kestrel web服务器, 有点类似于SpringBoot 默认内嵌了 tomcat. ASP.net core 还可以使用 Http.sys web服务器(仅限于Windows平台).
Program.cs文件中启用 Kestrel:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel(options =>
{
//待配置
});
Kestrel 的特性
- 安全性较好, 支持https, 在MVC项目中我们通常调用
app.UseHttpsRedirection()
即可将 http请求重定向到 https 端口 - 性能很好, 早期的 Kestrel 是基于流行的libuv 异步I/O库
- 运行方便, 一行代码即可启动我们的应用.
dotnet MyApp.dll
Kestrel 设置监听端口
Kestrel 默认监听5000和5001端口, 我们可以在 appsettings.json 中修改端口, 也可在命令行中加--urls 指定.
dotnet MyApp.dll
donet MyApp.dll --urls "http://localhost:8000;http://localhost:8001"
appsettings.json 文件:
{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
},
"Https": {
"Url": "https://localhost:5001"
}
}
}
}
Kestrel 选择环境
如果使用VS 开发工具, 它会自动读取 Properties/launchSetting.json 文件的profile设置.
如果使用命令行启动应用, 需要加上 --launch-profile
参数, 这时程序也会加载 launchSetting.json 文件 , 比如:
dotnet run --launch-profile="MyWeb"
launchSetting.json 文件内容:
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56833",
"sslPort": 0
}
},
"profiles": {
"MyWeb": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5284",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
关于 https
- UseHttpsRedirection 使用 HTTP(但重定向到 HTTPS)对终结点进行的请求失败,并返回 ERR_INVALID_REDIRECT on the CORS preflight request。
- Web API 项目推荐禁用 http 请求, 而不是通过 UseHttpsRedirection 进行https重定向
- 如果不指定证书,也可以使用 https,不过这使用的是默认的配置,只能用在 localhost 中。
参考
https://www.cnblogs.com/jackyfei/p/16416868.html
https://www.cnblogs.com/jackyfei/p/16586097.html
https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0
https://www.tektutorialshub.com/asp-net-core/asp-net-core-kestrel-web-server/
https://geeksarray.com/blog/aspnet-core-application-and-kestrel-web-server-settings
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律