ASPNET Core 2.x中的Kestrel服务器  何时一起使用Kestrel和反向代理服务器?  如何在ASP.NET CORE APP中使用KESTREL  Kestrel 选项  终端配置 URL prefixes 下一步

ASPNET Core 2.x中的Kestrel服务器
 何时一起使用Kestrel和反向代理服务器?
 如何在ASP.NET CORE APP中使用KESTREL
 Kestrel 选项
 终端配置
URL prefixes
下一步

原文链接

Kestrel是一个基于libuv的跨平台ASP.NET Core web服务器,libuv是一个跨平台的异步I/O库。ASP.NET Core模板项目使用Kestrel作为默认的web服务器。

Kestrel支持以下功能:

  • HTTPS
  • 用于启用不透明升级的WebSockets
  • 位于Nginx之后的高性能Unix sockets

Kestrel 被.NET Core支持的所有平台和版本所支持

查看和下载示例代码

ASP.NET CORE 2.x

     你可以单独或者与反向代理服务器(如 IIS, Nginx, or Apache)一起使用Kestrel。反向代理从互联网接受HTTP请求,预处理后转发给Kestrel.

ASPNET Core 2.x中的Kestrel服务器
 何时一起使用Kestrel和反向代理服务器?
 如何在ASP.NET CORE APP中使用KESTREL
 Kestrel 选项
 终端配置
URL prefixes
下一步

ASPNET Core 2.x中的Kestrel服务器
 何时一起使用Kestrel和反向代理服务器?
 如何在ASP.NET CORE APP中使用KESTREL
 Kestrel 选项
 终端配置
URL prefixes
下一步

如果Kestrel仅暴露与内网中,有或没有反向代理的配置。

   一个需要反向代理的场景是,你有多个需要在一个服务器上运行并共享同一端口的应用。因为Kestrel不支持在多进程间共享同一端口和同一个IP,在此情况下无法工作。当你配置Kestrel监听某个端口时,它会接管所有的流量,而不管主机标头是什么。反向代理可以共享出多个端口,然后转发给Ketrel的唯一IP和端口。

    即时反向代理不是必须的,但在某些场景下,使用反向代理是一个更好的选择:

  • 它可以限定你面对的网络区域.
  • 它可以提供多一个附加层,以提供附加的的防护.
  • 它可以更好地与现有架构集成。
  • 使用它也可以简化负载均衡和SSL设置 -- 只要你的反向代理服务器需要SSL证书,并且该服务器可以和你的应用在内部网中通过普通HTTP进行通信。

 如何在ASP.NET CORE APP中使用KESTREL

 ASP.NET CORE 2.x

    Microsoft.AspNetCore.Server.Kestrel 包已经包含在 Microsoft.AspNetCore.All metapackage中.

ASP.NET Core 工程模板缺省使用 Kestrel 。在 Program.cs中, 模板代码为 CreateDefaultBuilder, 它用这句语句调用 UseKestrel :

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args) 
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Listen(IPAddress.Loopback, 5000);
            options.Listen(IPAddress.Loopback, 5001, listenOptions =>
            {
                listenOptions.UseHttps("testCert.pfx", "testPassword");
            });
        })
        .Build();

 如果你要配置Kestrel选项, 请在 Program.cs 如下例所示调用 UseKestrel :

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Listen(IPAddress.Loopback, 5000);
            options.Listen(IPAddress.Loopback, 5001, listenOptions =>
            {
                listenOptions.UseHttps("testCert.pfx", "testPassword");
            });
        })
        .Build();

 Kestrel 选项

    Kestrel web server有一些约束选项,做面对互联网的不是时会非常用用。下面是你能设置的一些限制条件:

  • 最大连接客户数
  • 最大请求体大小Maximum request body size
  • 最小请求提数据率Minimum request body data rate

KestrelServerLimits 类的实例.

最大连接客户数

参考一下代码:

.UseKestrel(options =>
{
    options.Limits.MaxConcurrentConnections = 100;
    options.Limits.MaxConcurrentUpgradedConnections = 100;
    options.Limits.MaxRequestBodySize = 10 * 1024;
    options.Limits.MinRequestBodyDataRate =
        new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    options.Limits.MinResponseDataRate =
        new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    options.Listen(IPAddress.Loopback, 5000);
    options.Listen(IPAddress.Loopback, 5001, listenOptions =>
    {
        listenOptions.UseHttps("testCert.pfx", "testPassword");
    });
})

Maximum request body size

    缺省值为30,000,000byte, 大约是28.6MB。

   在ASP .NET CORE MVC 的APP中,建议在action方法中使用 RequestSizeLimit 属性来重写它:

[RequestSizeLimit(100000000)]
public IActionResult MyActionMethod()

  下面是一个配置整个应用内每一个请求的Maximum request body size的例子:

.UseKestrel(options =>
{
    options.Limits.MaxConcurrentConnections = 100;
    options.Limits.MaxConcurrentUpgradedConnections = 100;
    options.Limits.MaxRequestBodySize = 10 * 1024;
    options.Limits.MinRequestBodyDataRate =
        new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    options.Limits.MinResponseDataRate =
        new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    options.Listen(IPAddress.Loopback, 5000);
    options.Listen(IPAddress.Loopback, 5001, listenOptions =>
    {
        listenOptions.UseHttps("testCert.pfx", "testPassword");
    });
})

   你也可以在一个中间件中设置特定请求的值:

app.Run(async (context) =>
{
    context.Features.Get<IHttpMaxRequestBodySizeFeature>()
        .MaxRequestBodySize = 10 * 1024
    context.Features.Get<IHttpMinRequestBodyDataRateFeature>()
        .MinDataRate = new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    context.Features.Get<IHttpMinResponseDataRateFeature>()
        .MinDataRate = new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));


 终端配置

ASP.NET CORE 2.x:   

  缺省情况下,ASP.NET CORE绑定 http://localhost:5000. 通过在KestrelServerOptions上调用Listen 或者ListenUnixSocket方法可以配置Kestrel监听的URL和端口。(UseUrls, urls命令行参数,ASPNETCORE_URLS环境变量也能工作,定有一些限制,参考这里

 绑定到一个TCP socket

  一下,Listen 方法绑定一个TCP socket,  lumbda 选项配置一个SSL验证:

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Listen(IPAddress.Loopback, 5000);
            options.Listen(IPAddress.Loopback, 5001, listenOptions =>
            {
                listenOptions.UseHttps("testCert.pfx", "testPassword");
            });
        })
        .Build();

    请注意这个例子是如何用ListenOptions为部分终端配置SSL的。你可以用同一个API为部分终端配置其他Kestrel设置。

   在windows系统中,你可以使用PowerShell的命令 New-SelfSignedCertificate生成自签名SLL证书,当然也有其他更好用的第三方工具生成你的自签名证书,如:

Setting up HTTPS for development.

绑定到Unix socket

You can listen on a Unix socket for improved performance with Nginx, as shown in this example:

.UseKestrel(options =>
{
    options.ListenUnixSocket("/tmp/kestrel-test.sock");
    options.ListenUnixSocket("/tmp/kestrel-test.sock", listenOptions =>
    {
        listenOptions.UseHttps("testCert.pfx", "testpassword");
    });
})

Port 0

如果你指定端口号为0, Kestrel 会动态绑定一个可用的端口.下面的例子显示如何找到Kestrel运行时实际绑定了哪个端口:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    var serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();

    app.UseStaticFiles();

    app.Run(async (context) =>
    {
        context.Response.ContentType = "text/html";
        await context.Response
            .WriteAsync("<p>Hosted by Kestrel</p>");

        if (serverAddressesFeature != null)
        {
            await context.Response
                .WriteAsync("<p>Listening on the following addresses: " +
                    string.Join(", ", serverAddressesFeature.Addresses) +
                    "</p>");
        }

        await context.Response.WriteAsync($"<p>Request URL: {context.Request.GetDisplayUrl()}<p>");
    });
}

UserUrsl的限制

 你可以通过调用UseUrls方法,或者使用urls命令行参数,或者使用ASPNETCORE_URLS环境变量来配置终端。这在你想让你的代码工作于其他服务器而不是KESTREL时很有用。然后,请注意避免下面这些限制:

  • 不能在这些方法中使用SSL
  • 如果你同时使用Listen方法和UseUrls,Listen终端会重写UseUrls终端

IIS的终端配置

 如果你使用IIS,绑定到IIS的的URL将重写其他所有通过调用LisrtenorUseUrls设置的绑定。 For more information, see Introduction to ASP.NET Core Module.

URL prefixes

如果你调用UseUrls或使用urls命令行参数或ASPNETCORE_URLS环境变量,URL prefixes可以是以下格式:

ASP.NET CORE 2.x:

仅有HTTP URL prefixes是合法的;当你使用UseUrls配置URL绑定时,Kestrel并不支持SSL。

  • 有小数点的IPv4地址

    http://65.55.39.10:80/
    

    0.0.0.0 is a special case that binds to all IPv4 addresses.

  • 有小数点的IPv6地址

    http://[0:0:0:0:0:ffff:4137:270a]:80/ 
    

    [::] is the IPv6 equivalent of IPv4 0.0.0.0.

  • 有小数点的主机名

    http://contoso.com:80/
    http://*:80/
    

    Host names, *, and +, are not special. Anything that is not a recognized IP address or "localhost" will bind to all IPv4 and IPv6 IPs. If you need to bind different host names to different ASP.NET Core applications on the same port, use HTTP.sys or a reverse proxy server such as IIS, Nginx, or Apache.

  • 端口地址的"Localhost" 或回调 IP地址

    http://localhost:5000/
    http://127.0.0.1:5000/
    http://[::1]:5000/
    

    当指定localhost时,Kestrel会尝试绑定IPV4和IPV6的回调界面。如果请求端口在两个回调界面上都被其他服务使用,Ketrel会启动失败。如果因为其他原因(通常是因为IPV6不被支持)使得两个回调界面都不可用,Kestrel会记录一个报警。

下一步

进一步的信息,请访问以下资源:

ASP.NET CORE 2.x: