Kestrel服務(wù)器
Kestrel 服務(wù)器是什么
Kestrel 這個(gè)詞的意思是紅隼(小猛禽). 之前的 ASP.NET 應(yīng)用深度綁定IIS服務(wù), 跨平臺(tái)和部署都是問題, 現(xiàn)在的 ASP.NET core 應(yīng)用默認(rèn)使用了 Kestrel web服務(wù)器, 有點(diǎn)類似于SpringBoot 默認(rèn)內(nèi)嵌了 tomcat. ASP.net core 還可以使用 Http.sys web服務(wù)器(僅限于Windows平臺(tái)).
Program.cs文件中啟用 Kestrel:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel(options =>
{
//待配置
});
Kestrel 的特性
- 安全性較好, 支持https, 在MVC項(xiàng)目中我們通常調(diào)用
app.UseHttpsRedirection()即可將 http請(qǐng)求重定向到 https 端口 - 性能很好, 早期的 Kestrel 是基于流行的libuv 異步I/O庫(kù)
- 運(yùn)行方便, 一行代碼即可啟動(dòng)我們的應(yīng)用.
dotnet MyApp.dll
Kestrel 設(shè)置監(jiān)聽端口
Kestrel 默認(rèn)監(jiān)聽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 選擇環(huán)境
如果使用VS 開發(fā)工具, 它會(huì)自動(dòng)讀取 Properties/launchSetting.json 文件的profile設(shè)置.
如果使用命令行啟動(dòng)應(yīng)用, 需要加上 --launch-profile 參數(shù), 這時(shí)程序也會(huì)加載 launchSetting.json 文件 , 比如:
dotnet run --launch-profile="MyWeb"
launchSetting.json 文件內(nèi)容:
{
"$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"
}
}
}
}
關(guān)于 https
- UseHttpsRedirection 使用 HTTP(但重定向到 HTTPS)對(duì)終結(jié)點(diǎn)進(jìn)行的請(qǐng)求失敗,并返回 ERR_INVALID_REDIRECT on the CORS preflight request。
- Web API 項(xiàng)目推薦禁用 http 請(qǐng)求, 而不是通過 UseHttpsRedirection 進(jìn)行https重定向
- 如果不指定證書,也可以使用 https,不過這使用的是默認(rèn)的配置,只能用在 localhost 中。
參考
http://www.rzrgm.cn/jackyfei/p/16416868.html
http://www.rzrgm.cn/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

浙公網(wǎng)安備 33010602011771號(hào)