Kestrel服务器

发布时间 2023-04-12 20:52:27作者: harrychinese

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
    donet  MyApp.dll --urls "http://localhost:8000;http://localhost:8001"
    
  • 部署和配置方便
    Kestrel 默认监听5000和5001端口, 我们可以在 appsettings.json 中修改端口, 也可在命令行中加--urls 指定.
{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://localhost:5000"
      },
      "Https": {
        "Url": "https://localhost:5001"
      }
    }
  }
}

关于 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=""></https:></https:></https:></https:></https:>