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

  1. UseHttpsRedirection 使用 HTTP(但重定向到 HTTPS)对终结点进行的请求失败,并返回 ERR_INVALID_REDIRECT on the CORS preflight request。
  2. Web API 项目推荐禁用 http 请求, 而不是通过 UseHttpsRedirection 进行https重定向
  3. 如果不指定证书,也可以使用 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

posted @ 2023-04-12 20:48  harrychinese  阅读(284)  评论(0编辑  收藏  举报