ASP.NET Core 中的 Kestrel 網頁伺服器實作Kestrel web server implementation in ASP.NET Core

作者:Tom DykstraChris RossStephen HalterBy Tom Dykstra, Chris Ross, and Stephen Halter

Kestrel 是 ASP.NET Core 的跨平台網頁伺服器Kestrel is a cross-platform web server for ASP.NET Core. Kestrel 是 ASP.NET Core 專案範本中預設隨附的網頁伺服器。Kestrel is the web server that's included by default in ASP.NET Core project templates.

Kestrel 支援下列案例:Kestrel supports the following scenarios:

  • HTTPSHTTPS
  • 用來啟用 WebSockets 的不透明升級Opaque upgrade used to enable WebSockets
  • Nginx 背後的高效能 Unix 通訊端Unix sockets for high performance behind Nginx
  • HTTP/2 (macOS 上除外†)HTTP/2 (except on macOS†)

†未來版本的 macOS 上將會支援 HTTP/2。†HTTP/2 will be supported on macOS in a future release.

  • HTTPSHTTPS
  • 用來啟用 WebSockets 的不透明升級Opaque upgrade used to enable WebSockets
  • Nginx 背後的高效能 Unix 通訊端Unix sockets for high performance behind Nginx

.NET Core 支援的所有平台和版本都支援 Kestrel。Kestrel is supported on all platforms and versions that .NET Core supports.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

HTTP/2 支援HTTP/2 support

如果符合下列基本需求,則可以針對 ASP.NET Core 應用程式使用 HTTP/2HTTP/2 is available for ASP.NET Core apps if the following base requirements are met:

  • 作業系統†Operating system†
    • Windows Server 2016/Windows 10 或更新版本‡Windows Server 2016/Windows 10 or later‡
    • Linux 含 OpenSSL 1.0.2 或更新版本 (例如 Ubuntu 16.04 或更新版本)Linux with OpenSSL 1.0.2 or later (for example, Ubuntu 16.04 or later)
  • 目標 Framework:.NET Core 2.2 或更新版本Target framework: .NET Core 2.2 or later
  • Application-Layer Protocol Negotiation (ALPN) 連線Application-Layer Protocol Negotiation (ALPN) connection
  • TLS 1.2 或更新版本連線TLS 1.2 or later connection

†未來版本的 macOS 上將會支援 HTTP/2。†HTTP/2 will be supported on macOS in a future release. ‡Kestrel 在 Windows Server 2012 R2 與 Windows 8.1 對 HTTP/2 的支援有限。‡Kestrel has limited support for HTTP/2 on Windows Server 2012 R2 and Windows 8.1. 支援有限的原因是這些作業系統上的支援 TLS 密碼編譯套件清單有限。Support is limited because the list of supported TLS cipher suites available on these operating systems is limited. 可能需要使用橢圓曲線數位簽章演算法 (ECDSA) 產生的憑證來保護 TLS 連線。A certificate generated using an Elliptic Curve Digital Signature Algorithm (ECDSA) may be required to secure TLS connections.

如果已建立 HTTP/2 連線,HttpRequest.Protocol 會報告 HTTP/2If an HTTP/2 connection is established, HttpRequest.Protocol reports HTTP/2.

預設會停用 HTTP/2。HTTP/2 is disabled by default. 如需組態的詳細資訊,請參閱 Kestrel 選項ListenOptions. 通訊協定一節。For more information on configuration, see the Kestrel options and ListenOptions.Protocols sections.

何時搭配使用 Kestrel 與反向 ProxyWhen to use Kestrel with a reverse proxy

您可以單獨使用 Kestrel,或與 Internet Information Services (IIS)NginxApache 等「反向 Proxy 伺服器」 搭配使用。Kestrel can be used by itself or with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. 反向 Proxy 伺服器會從網路接收 HTTP 要求,然後轉送到 Kestrel。A reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.

Kestrel 用作邊緣 (網際網路對應) 網頁伺服器:Kestrel used as an edge (Internet-facing) web server:

Kestrel 不使用反向 Proxy 伺服器直接與網際網路通訊

Kestrel 用於反向 Proxy 組態中:Kestrel used in a reverse proxy configuration:

Kestrel 透過 IIS、Nginx 或 Apache 等反向 Proxy 伺服器間接與網際網路通訊

不論組態是否具有反向 Proxy 伺服器,對於從網際網路接收要求的 ASP.NET Core 2.1 或更新版本的應用程式來說,都是支援的裝載組態。Either configuration—with or without a reverse proxy server—is a supported hosting configuration for ASP.NET Core 2.1 or later apps that receive requests from the Internet.

Kestrel 用作不需要反向 Proxy 伺服器的 Edge Server 時,不支援在多個處理序之間共用相同的 IP 和連接埠。Kestrel used as an edge server without a reverse proxy server doesn't support sharing the same IP and port among multiple processes. 當 Kestrel 設定為接聽連接埠時,Kestrel 會處理該連接埠的所有流量,而不論要求的 Host 標頭為何。When Kestrel is configured to listen on a port, Kestrel handles all of the traffic for that port regardless of requests' Host headers. 可以共用連接埠的反向 Proxy 能夠在唯一的 IP 和連接埠上轉送要求給 Kestrel。A reverse proxy that can share ports has the ability to forward requests to Kestrel on a unique IP and port.

即使不需要反向 Proxy 伺服器,使用反向 Proxy 伺服器也是不錯的選擇。Even if a reverse proxy server isn't required, using a reverse proxy server might be a good choice.

反向 Proxy:A reverse proxy:

  • 可以限制它所主控之應用程式的公開介面區。Can limit the exposed public surface area of the apps that it hosts.
  • 提供額外的組態和防禦層。Provide an additional layer of configuration and defense.
  • 能夠與現有基礎結構更好地整合。Might integrate better with existing infrastructure.
  • 簡化負載平衡和安全通訊 (HTTPS) 組態。Simplify load balancing and secure communication (HTTPS) configuration. 只有反向 Proxy 伺服器需要 X.509 憑證,而且該伺服器可以使用一般 HTTP 與內部網路上的應用程式伺服器通訊。Only the reverse proxy server requires an X.509 certificate, and that server can communicate with your app servers on the internal network using plain HTTP.

警告

裝載於反向 Proxy 組態需要主機篩選Hosting in a reverse proxy configuration requires host filtering.

如何在 ASP.NET Core 應用程式中使用 KestrelHow to use Kestrel in ASP.NET Core apps

Microsoft.AspNetCore.Server.Kestrel 套件包含在 Microsoft.AspNetCore.App 中繼套件中 (ASP.NET Core 2.1 或更新版本)。The Microsoft.AspNetCore.Server.Kestrel package is included in the Microsoft.AspNetCore.App metapackage (ASP.NET Core 2.1 or later).

ASP.NET Core 專案範本預設會使用 Kestrel。ASP.NET Core project templates use Kestrel by default. Program.cs 中,範本程式碼會呼叫 CreateDefaultBuilder,而後者會在幕後呼叫 UseKestrelIn Program.cs, the template code calls CreateDefaultBuilder, which calls UseKestrel behind the scenes.

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

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

若要在呼叫 CreateDefaultBuilder 之後提供額外的設定,請使用 ConfigureKestrelTo provide additional configuration after calling CreateDefaultBuilder, use ConfigureKestrel:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            // Set properties and call methods on options
        });

如果應用程式未呼叫 CreateDefaultBuilder 來設定主機,請在呼叫 ConfigureKestrel 之前,先呼叫 UseKestrelIf the app doesn't call CreateDefaultBuilder to set up the host, call UseKestrel before calling ConfigureKestrel:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseKestrel()
        .UseIISIntegration()
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            // Set properties and call methods on options
        })
        .Build();

    host.Run();
}

若要在呼叫 CreateDefaultBuilder 之後提供額外的設定,請呼叫 UseKestrelTo provide additional configuration after calling CreateDefaultBuilder, call UseKestrel:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            // Set properties and call methods on options
        });

Kestrel 選項Kestrel options

Kestrel 網頁伺服器所含的條件約束組態選項,在網際網路對應部署方面特別有用。The Kestrel web server has constraint configuration options that are especially useful in Internet-facing deployments.

請在 KestrelServerOptions 類別的 Limits 屬性上設定條件約束。Set constraints on the Limits property of the KestrelServerOptions class. Limits 屬性會保存 KestrelServerLimits 類別的執行個體。The Limits property holds an instance of the KestrelServerLimits class.

下列範例會使用 Microsoft.AspNetCore.Server.Kestrel.Core 命名空間;The following examples use the Microsoft.AspNetCore.Server.Kestrel.Core namespace:

using Microsoft.AspNetCore.Server.Kestrel.Core;

Keep-alive 逾時Keep-alive timeout

KeepAliveTimeout

取得或設定 Keep-alive 逾時 (英文)。Gets or sets the keep-alive timeout. 預設為 2 分鐘。Defaults to 2 minutes.

.ConfigureKestrel((context, 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");
    });
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
        });

用戶端連線數目上限Maximum client connections

MaxConcurrentConnections
MaxConcurrentUpgradedConnections

可以使用下列程式碼,針對整個應用程式設定同時開啟的 TCP 連線數目上限:The maximum number of concurrent open TCP connections can be set for the entire app with the following code:

.ConfigureKestrel((context, 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");
    });
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Limits.MaxConcurrentConnections = 100;
        });

已經從 HTTP 或 HTTPS 升級為另一個通訊協定 (例如,在 WebSocket 要求中) 的連線,有其個別限制。There's a separate limit for connections that have been upgraded from HTTP or HTTPS to another protocol (for example, on a WebSockets request). 升級連線之後,它不會納入 MaxConcurrentConnections 限制。After a connection is upgraded, it isn't counted against the MaxConcurrentConnections limit.

.ConfigureKestrel((context, 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");
    });
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Limits.MaxConcurrentUpgradedConnections = 100;
        });

連線數目上限預設為無限制 (null)。The maximum number of connections is unlimited (null) by default.

要求主體大小上限Maximum request body size

MaxRequestBodySize

預設的要求主體大小上限是 30,000,000 個位元組,大約 28.6 MB。The default maximum request body size is 30,000,000 bytes, which is approximately 28.6 MB.

若要覆寫 ASP.NET Core MVC 應用程式中的限制,建議的方式是在動作方法上使用 RequestSizeLimitAttribute屬性:The recommended approach to override the limit in an ASP.NET Core MVC app is to use the RequestSizeLimitAttribute attribute on an action method:

[RequestSizeLimit(100000000)]
public IActionResult MyActionMethod()

以下範例會示範如何設定應用程式、每個要求的條件約束:Here's an example that shows how to configure the constraint for the app on every request:

.ConfigureKestrel((context, 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");
    });
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Limits.MaxRequestBodySize = 10 * 1024;
        });

您可以在中介軟體中覆寫特定要求的設定:You can override the setting on a specific request in middleware:

app.Run(async (context) =>
{
    context.Features.Get<IHttpMaxRequestBodySizeFeature>()
        .MaxRequestBodySize = 10 * 1024;

    var minRequestRateFeature = 
        context.Features.Get<IHttpMinRequestBodyDataRateFeature>();
    var minResponseRateFeature = 
        context.Features.Get<IHttpMinResponseDataRateFeature>();

    if (minRequestRateFeature != null)
    {
        minRequestRateFeature.MinDataRate = new MinDataRate(
            bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    }

    if (minResponseRateFeature != null)
    {
        minResponseRateFeature.MinDataRate = new MinDataRate(
            bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    }

如果應用程式已開始讀取要求之後,才嘗試設定要求的限制,則會擲回例外狀況。An exception is thrown if you attempt to configure the limit on a request after the app has started to read the request. 有一個 IsReadOnly 屬性會指出 MaxRequestBodySize 屬性處於唯讀狀態,這表示要設定限制已經太遲。There's an IsReadOnly property that indicates if the MaxRequestBodySize property is in read-only state, meaning it's too late to configure the limit.

當應用程式是在 ASP.NET Core 模組後方於處理序外執行時,Kestrel 的要求本文大小限制將會被停用,因為 IIS 已經設定限制。When an app is run out-of-process behind the ASP.NET Core Module, Kestrel's request body size limit is disabled because IIS already sets the limit.

要求主體資料速率下限Minimum request body data rate

MinRequestBodyDataRate
MinResponseDataRate

如果資料是以指定的速率 (位元組/秒) 傳入,Kestrel 會每秒檢查一次。Kestrel checks every second if data is arriving at the specified rate in bytes/second. 如果速率低於下限值,則連線會逾時。寬限期是 Kestrel 提供給用戶端的時間量,以便將其傳送速率提高到下限值;在這段期間不會檢查速率。If the rate drops below the minimum, the connection is timed out. The grace period is the amount of time that Kestrel gives the client to increase its send rate up to the minimum; the rate isn't checked during that time. 寬限期可協助避免中斷連線,這是由於 TCP 緩慢啟動而一開始以低速傳送資料所造成。The grace period helps avoid dropping connections that are initially sending data at a slow rate due to TCP slow-start.

預設速率下限為 240 個位元組/秒,寬限期為 5 秒。The default minimum rate is 240 bytes/second with a 5 second grace period.

速率下限也適用於回應。A minimum rate also applies to the response. 除了屬性中具有 RequestBodyResponse 以及介面名稱之外,用來設定要求限制和回應限制的程式碼都相同。The code to set the request limit and the response limit is the same except for having RequestBody or Response in the property and interface names.

以下範例示範如何在 Program.cs 中設定資料速率下限:Here's an example that shows how to configure the minimum data rates in Program.cs:

.ConfigureKestrel((context, 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");
    });
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Limits.MinRequestBodyDataRate =
                new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
            options.Limits.MinResponseDataRate =
                new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
        });

您可以覆寫中介軟體中每個要求的最小速率限制:You can override the minimum rate limits per request in middleware:

app.Run(async (context) =>
{
    context.Features.Get<IHttpMaxRequestBodySizeFeature>()
        .MaxRequestBodySize = 10 * 1024;

    var minRequestRateFeature = 
        context.Features.Get<IHttpMinRequestBodyDataRateFeature>();
    var minResponseRateFeature = 
        context.Features.Get<IHttpMinResponseDataRateFeature>();

    if (minRequestRateFeature != null)
    {
        minRequestRateFeature.MinDataRate = new MinDataRate(
            bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    }

    if (minResponseRateFeature != null)
    {
        minResponseRateFeature.MinDataRate = new MinDataRate(
            bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
    }

因為通訊協定對要求多工的支援,所以 HTTP/2 不支援以每一要求基礎修改速率限制,進而使先前範例中所參考的所有速率功能都不會出現在 HTTP/2 要求的 HttpContext.Features 中。Neither rate feature referenced in the prior sample are present in HttpContext.Features for HTTP/2 requests because modifying rate limits on a per-request basis isn't supported for HTTP/2 due to the protocol's support for request multiplexing. 透過 KestrelServerOptions.Limits 設定的全伺服器速率限制皆仍套用至 HTTP/1.x 及 HTTP/2 連線。Server-wide rate limits configured via KestrelServerOptions.Limits still apply to both HTTP/1.x and HTTP/2 connections.

要求標頭逾時Request headers timeout

RequestHeadersTimeout

取得或設定伺服器花費在接收要求標頭的時間上限。Gets or sets the maximum amount of time the server spends receiving request headers. 預設為 30 秒。Defaults to 30 seconds.

.ConfigureKestrel((context, 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");
    });
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
        });

每個連線的資料流數目上限Maximum streams per connection

Http2.MaxStreamsPerConnection 會限制每個 HTTP/2 連線的同時要求資料流數目。Http2.MaxStreamsPerConnection limits the number of concurrent request streams per HTTP/2 connection. 超出的資料流會被拒絕。Excess streams are refused.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.Http2.MaxStreamsPerConnection = 100;
        });

預設值為 100。The default value is 100.

標頭表格大小Header table size

HPACK 解碼器可解壓縮 HTTP/2 連線的 HTTP 標頭。The HPACK decoder decompresses HTTP headers for HTTP/2 connections. Http2.HeaderTableSize 會限制 HPACK 解碼器所使用的標頭壓縮表格大小。Http2.HeaderTableSize limits the size of the header compression table that the HPACK decoder uses. 這個值是以八位元提供,而且必須大於零 (0)。The value is provided in octets and must be greater than zero (0).

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.Http2.HeaderTableSize = 4096;
        });

預設值為 4096。The default value is 4096.

框架大小上限Maximum frame size

Http2.MaxFrameSize 表示要接收的 HTTP/2 連線框架承載大小上限。Http2.MaxFrameSize indicates the maximum size of the HTTP/2 connection frame payload to receive. 這個值是以八位元提供,而且必須介於 2^14 (16,384) 到 2^24-1 (16,777,215) 之間。The value is provided in octets and must be between 2^14 (16,384) and 2^24-1 (16,777,215).

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.Http2.MaxFrameSize = 16384;
        });

預設值為 2^14 (16,384)。The default value is 2^14 (16,384).

要求標頭大小上限Maximum request header size

Http2.MaxRequestHeaderFieldSize 以八位元表示要求標頭值的允許大小上限。Http2.MaxRequestHeaderFieldSize indicates the maximum allowed size in octets of request header values. 此限制皆共同套用至已壓縮及未壓縮代表中的名稱與值。This limit applies to both name and value together in their compressed and uncompressed representations. 此值必須大於零 (0)。The value must be greater than zero (0).

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.Http2.MaxRequestHeaderFieldSize = 8192;
        });

預設值為 8,192。The default value is 8,192.

初始連線視窗大小Initial connection window size

Http2.InitialConnectionWindowSize 會以位元組表示伺服器緩衝每個連線之所有要求 (資料流) 單次彙總的要求內容資料上限。Http2.InitialConnectionWindowSize indicates the maximum request body data in bytes the server buffers at one time aggregated across all requests (streams) per connection. 要求也皆受 Http2.InitialStreamWindowSize 所限制。Requests are also limited by Http2.InitialStreamWindowSize. 此值必須大於或等於 65,535,且小於 2^31 (2,147,483,648)。The value must be greater than or equal to 65,535 and less than 2^31 (2,147,483,648).

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.Http2.InitialConnectionWindowSize = 131072;
        });

預設值為 128 KB (131,072)。The default value is 128 KB (131,072).

初始資料流視窗大小Initial stream window size

Http2.InitialStreamWindowSize 會以位元組表示每個要求 (資料流) 單次伺服器緩衝的要求內容資料上限。Http2.InitialStreamWindowSize indicates the maximum request body data in bytes the server buffers at one time per request (stream). 要求也皆受 Http2.InitialStreamWindowSize 所限制。Requests are also limited by Http2.InitialStreamWindowSize. 此值必須大於或等於 65,535,且小於 2^31 (2,147,483,648)。The value must be greater than or equal to 65,535 and less than 2^31 (2,147,483,648).

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.Http2.InitialStreamWindowSize = 98304;
        });

預設值為 96 KB (98,304)。The default value is 96 KB (98,304).

如需其他 Kestrel 選項和限制的資訊,請參閱:For information about other Kestrel options and limits, see:

端點組態Endpoint configuration

ASP.NET Core 預設會繫結至:By default, ASP.NET Core binds to:

  • http://localhost:5000
  • https://localhost:5001 (當有本機開發憑證存在時)https://localhost:5001 (when a local development certificate is present)

使用以下各項指定 URL:Specify URLs using the:

  • ASPNETCORE_URLS 環境變數。ASPNETCORE_URLS environment variable.
  • --urls 命令列引數。--urls command-line argument.
  • urls 主機組態索引鍵。urls host configuration key.
  • UseUrls 擴充方法。UseUrls extension method.

使用這些方法提供的值可以是一或多個 HTTP 和 HTTPS 端點 (如果有預設憑證可用則為 HTTPS)。The value provided using these approaches can be one or more HTTP and HTTPS endpoints (HTTPS if a default cert is available). 將值設定為以分號分隔的清單 (例如,"Urls": "http://localhost:8000;http://localhost:8001")。Configure the value as a semicolon-separated list (for example, "Urls": "http://localhost:8000;http://localhost:8001").

如需有關這些方法的詳細資訊,請參閱伺服器 URL覆寫設定For more information on these approaches, see Server URLs and Override configuration.

開發憑證會建立於:A development certificate is created:

有些瀏覽器需要您授與明確的權限給瀏覽器,才能信任本機開發憑證。Some browsers require that you grant explicit permission to the browser to trust the local development certificate.

ASP.NET Core 2.1 和更新版本的專案範本會將應用程式設定為預設於 HTTPS 上執行,並包含 HTTPS 重新導向和 HSTS 支援ASP.NET Core 2.1 and later project templates configure apps to run on HTTPS by default and include HTTPS redirection and HSTS support.

請在 KestrelServerOptions 上呼叫 ListenListenUnixSocket 方法,來為 Kestrel 設定 URL 首碼和連接埠。Call Listen or ListenUnixSocket methods on KestrelServerOptions to configure URL prefixes and ports for Kestrel.

UseUrls--urls 命令列引數、urls 主機組態索引鍵和 ASPNETCORE_URLS 環境變數同樣有效,但卻有本節稍後註明的限制 (針對 HTTPS 端點組態必須有預設憑證可用)。UseUrls, the --urls command-line argument, urls host configuration key, and the ASPNETCORE_URLS environment variable also work but have the limitations noted later in this section (a default certificate must be available for HTTPS endpoint configuration).

ASP.NET Core 2.1 或更新版本 KestrelServerOptions 設定:ASP.NET Core 2.1 or later KestrelServerOptions configuration:

ConfigureEndpointDefaults(Action<ListenOptions>)ConfigureEndpointDefaults(Action<ListenOptions>)

指定組態 Action 以針對每個指定端點執行。Specifies a configuration Action to run for each specified endpoint. 呼叫 ConfigureEndpointDefaults 多次會以最後一個指定的 Action 取代之前的 ActionCalling ConfigureEndpointDefaults multiple times replaces prior Actions with the last Action specified.

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.ConfigureKestrel(serverOptions =>
        {
            serverOptions.ConfigureEndpointDefaults(configureOptions =>
            {
                configureOptions.NoDelay = true;
            });
        });
        webBuilder.UseStartup<Startup>();
    });
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.ConfigureEndpointDefaults(configureOptions =>
            {
                configureOptions.NoDelay = true;
            });
        });

ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)

指定組態 Action 以針對每個 HTTPS 端點執行。Specifies a configuration Action to run for each HTTPS endpoint. 呼叫 ConfigureHttpsDefaults 多次會以最後一個指定的 Action 取代之前的 ActionCalling ConfigureHttpsDefaults multiple times replaces prior Actions with the last Action specified.

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.ConfigureKestrel(serverOptions =>
        {
            serverOptions.ConfigureHttpsDefaults(options =>
            {
                // certificate is an X509Certificate2
                options.ServerCertificate = certificate;
            });
        });
        webBuilder.UseStartup<Startup>();
    });
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.ConfigureHttpsDefaults(httpsOptions =>
            {
                // certificate is an X509Certificate2
                httpsOptions.ServerCertificate = certificate;
            });
        });

Configure(IConfiguration)Configure(IConfiguration)

建立設定載入器來設定以 IConfiguration 作為輸入的 Kestrel。Creates a configuration loader for setting up Kestrel that takes an IConfiguration as input. 組態的範圍必須限於 Kestrel 的組態區段。The configuration must be scoped to the configuration section for Kestrel.

ListenOptions.UseHttpsListenOptions.UseHttps

設定 Kestrel 使用 HTTPS。Configure Kestrel to use HTTPS.

ListenOptions.UseHttps 延伸模組:ListenOptions.UseHttps extensions:

  • UseHttps – 設定 Kestrel 以與 HTTPS 預設憑證搭配使用。UseHttps – Configure Kestrel to use HTTPS with the default certificate. 如果未設定預設憑證,會擲回例外狀況。Throws an exception if no default certificate is configured.
  • UseHttps(string fileName)
  • UseHttps(string fileName, string password)
  • UseHttps(string fileName, string password, Action<HttpsConnectionAdapterOptions> configureOptions)
  • UseHttps(StoreName storeName, string subject)
  • UseHttps(StoreName storeName, string subject, bool allowInvalid)
  • UseHttps(StoreName storeName, string subject, bool allowInvalid, StoreLocation location)
  • UseHttps(StoreName storeName, string subject, bool allowInvalid, StoreLocation location, Action<HttpsConnectionAdapterOptions> configureOptions)
  • UseHttps(X509Certificate2 serverCertificate)
  • UseHttps(X509Certificate2 serverCertificate, Action<HttpsConnectionAdapterOptions> configureOptions)
  • UseHttps(Action<HttpsConnectionAdapterOptions> configureOptions)

ListenOptions.UseHttps 參數:ListenOptions.UseHttps parameters:

  • filename 是憑證檔案的路徑和檔案名稱,它相對於包含應用程式內容檔案的目錄。filename is the path and file name of a certificate file, relative to the directory that contains the app's content files.
  • password 是存取 X.509 憑證資料所需的密碼。password is the password required to access the X.509 certificate data.
  • configureOptions 是設定 HttpsConnectionAdapterOptionsActionconfigureOptions is an Action to configure the HttpsConnectionAdapterOptions. 傳回 ListenOptionsReturns the ListenOptions.
  • storeName 是要從中載入憑證的憑證存放區。storeName is the certificate store from which to load the certificate.
  • subject 是憑證的主體名稱。subject is the subject name for the certificate.
  • allowInvalid 表示是否應該考慮無效的憑證,例如自我簽署憑證。allowInvalid indicates if invalid certificates should be considered, such as self-signed certificates.
  • location 是要從中載入憑證的存放區位置。location is the store location to load the certificate from.
  • serverCertificate 是 X.509 憑證。serverCertificate is the X.509 certificate.

在生產環境中,必須明確設定 HTTPS。In production, HTTPS must be explicitly configured. 至少必須提供預設憑證。At a minimum, a default certificate must be provided.

支援的組態描述如下:Supported configurations described next:

  • 無組態No configuration
  • 從組態取代預設憑證Replace the default certificate from configuration
  • 變更程式碼中的預設值Change the defaults in code

無組態No configuration

Kestrel 會接聽 http://localhost:5000https://localhost:5001 (如果預設憑證可用的話)。Kestrel listens on http://localhost:5000 and https://localhost:5001 (if a default cert is available).

從組態取代預設憑證Replace the default certificate from configuration

CreateDefaultBuilder 預設會呼叫 serverOptions.Configure(context.Configuration.GetSection("Kestrel")) 以載入 Kestrel 設定。CreateDefaultBuilder calls serverOptions.Configure(context.Configuration.GetSection("Kestrel")) by default to load Kestrel configuration. Kestrel 可以使用預設的 HTTPS 應用程式設定組態結構描述。A default HTTPS app settings configuration schema is available for Kestrel. 設定多個端點,包括 URL 和要使用的憑證-從磁碟上的檔案,或是從憑證存放區。Configure multiple endpoints, including the URLs and the certificates to use, either from a file on disk or from a certificate store.

在下列 appsettings.json 範例中:In the following appsettings.json example:

  • AllowInvalid 設定為 true,允許使用無效的憑證 (例如,自我簽署憑證)。Set AllowInvalid to true to permit the use of invalid certificates (for example, self-signed certificates).
  • 任何未指定憑證 (接下來範例中的 HttpsDefaultCert) 的 HTTPS 端點會回復為 [憑證] > [預設] 下定義的憑證或開發憑證。Any HTTPS endpoint that doesn't specify a certificate (HttpsDefaultCert in the example that follows) falls back to the cert defined under Certificates > Default or the development certificate.
{
"Kestrel": {
  "EndPoints": {
    "Http": {
      "Url": "http://localhost:5000"
    },

    "HttpsInlineCertFile": {
      "Url": "https://localhost:5001",
      "Certificate": {
        "Path": "<path to .pfx file>",
        "Password": "<certificate password>"
      }
    },

    "HttpsInlineCertStore": {
      "Url": "https://localhost:5002",
      "Certificate": {
        "Subject": "<subject; required>",
        "Store": "<certificate store; required>",
        "Location": "<location; defaults to CurrentUser>",
        "AllowInvalid": "<true or false; defaults to false>"
      }
    },

    "HttpsDefaultCert": {
      "Url": "https://localhost:5003"
    },

    "Https": {
      "Url": "https://*:5004",
      "Certificate": {
      "Path": "<path to .pfx file>",
      "Password": "<certificate password>"
      }
    }
    },
    "Certificates": {
      "Default": {
        "Path": "<path to .pfx file>",
        "Password": "<certificate password>"
      }
    }
  }
}

除了針對任何憑證節點使用 [路徑] 和 [密碼] ,還可以使用憑證存放區欄位指定憑證。An alternative to using Path and Password for any certificate node is to specify the certificate using certificate store fields. 例如,[憑證] > [預設] 憑證可以指定為:For example, the Certificates > Default certificate can be specified as:

"Default": {
  "Subject": "<subject; required>",
  "Store": "<cert store; required>",
  "Location": "<location; defaults to CurrentUser>",
  "AllowInvalid": "<true or false; defaults to false>"
}

結構描述附註:Schema notes:

  • 端點名稱不區分大小寫。Endpoints names are case-insensitive. 例如,HTTPSHttps 都有效。For example, HTTPS and Https are valid.

  • Url 參數對每個端點而言都是必要的。The Url parameter is required for each endpoint. 此參數的格式等同於最上層 Urls 組態參數,但是它限制為單一值。The format for this parameter is the same as the top-level Urls configuration parameter except that it's limited to a single value.

  • 這些端點會取代最上層 Urls 組態中定義的端點,而不是新增至其中。These endpoints replace those defined in the top-level Urls configuration rather than adding to them. 透過 Listen 在程式碼中定義的端點,會與組態區段中定義的端點累計。Endpoints defined in code via Listen are cumulative with the endpoints defined in the configuration section.

  • Certificate 區段是選擇性的。The Certificate section is optional. 如果未指定 Certificate 區段,則會使用先前案例中所定義的預設值。If the Certificate section isn't specified, the defaults defined in earlier scenarios are used. 如果沒有預設值可供使用,伺服器就會擲回例外狀況,且無法啟動。If no defaults are available, the server throws an exception and fails to start.

  • Certificate 區段同時支援 [路徑] – [密碼] 和 [主旨] – [存放區] 憑證。The Certificate section supports both PathPassword and SubjectStore certificates.

  • 可以用這種方式定義任何數目的端點,只要它們不會導致連接埠衝突即可。Any number of endpoints may be defined in this way so long as they don't cause port conflicts.

  • options.Configure(context.Configuration.GetSection("Kestrel")) 會傳回 KestrelConfigurationLoader.Endpoint(string name, options => { }) 方法,此方法可用來補充已設定的端點設定:options.Configure(context.Configuration.GetSection("Kestrel")) returns a KestrelConfigurationLoader with an .Endpoint(string name, options => { }) method that can be used to supplement a configured endpoint's settings:

    options.Configure(context.Configuration.GetSection("Kestrel"))
        .Endpoint("HTTPS", opt =>
        {
            opt.HttpsOptions.SslProtocols = SslProtocols.Tls12;
        });
    

    您也可以直接存取 KestrelServerOptions.ConfigurationLoader 來保持反覆運算現有的載入器,例如 CreateDefaultBuilder 提供的載入器。You can also directly access KestrelServerOptions.ConfigurationLoader to keep iterating on the existing loader, such as the one provided by CreateDefaultBuilder.

  • 每個端點的組態區段可用於 Endpoint 方法的選項,因此可讀取自訂組態。The configuration section for each endpoint is a available on the options in the Endpoint method so that custom settings may be read.

  • 可以藉由使用另一個區段再次呼叫 options.Configure(context.Configuration.GetSection("Kestrel")) 而載入多個組態。Multiple configurations may be loaded by calling options.Configure(context.Configuration.GetSection("Kestrel")) again with another section. 只會使用最後一個組態,除非在先前的執行個體上已明確呼叫 LoadOnly the last configuration is used, unless Load is explicitly called on prior instances. 中繼套件不會呼叫 Load,如此可能會取代其預設組態區段。The metapackage doesn't call Load so that its default configuration section may be replaced.

  • KestrelConfigurationLoader 會將來自 KestrelServerOptions 的 API 的 Listen 系列鏡像為 Endpoint 多載,所以可在相同的位置設定程式碼和設定端點。KestrelConfigurationLoader mirrors the Listen family of APIs from KestrelServerOptions as Endpoint overloads, so code and config endpoints may be configured in the same place. 這些多載不使用名稱,並且只使用來自組態的預設組態。These overloads don't use names and only consume default settings from configuration.

變更程式碼中的預設值Change the defaults in code

ConfigureEndpointDefaultsConfigureHttpsDefaults 可以用來變更 ListenOptionsHttpsConnectionAdapterOptions 的預設設定,包括覆寫先前案例中指定的預設憑證。ConfigureEndpointDefaults and ConfigureHttpsDefaults can be used to change default settings for ListenOptions and HttpsConnectionAdapterOptions, including overriding the default certificate specified in the prior scenario. ConfigureEndpointDefaultsConfigureHttpsDefaults 應該在設定任何端點之前呼叫。ConfigureEndpointDefaults and ConfigureHttpsDefaults should be called before any endpoints are configured.

options.ConfigureEndpointDefaults(opt =>
{
    opt.NoDelay = true;
});

options.ConfigureHttpsDefaults(httpsOptions =>
{
    httpsOptions.SslProtocols = SslProtocols.Tls12;
});

SNI 的 Kestrel 支援Kestrel support for SNI

伺服器名稱指示 (SNI) 可以用於在相同的 IP 位址和連接埠上裝載多個網域。Server Name Indication (SNI) can be used to host multiple domains on the same IP address and port. SNI 若要運作,用戶端會在 TLS 信號交換期間傳送安全工作階段的主機名稱給伺服器,讓伺服器可以提供正確的憑證。For SNI to function, the client sends the host name for the secure session to the server during the TLS handshake so that the server can provide the correct certificate. 用戶端在 TLS 信號交換之後的安全工作階段期間,會使用所提供的憑證與伺服器進行加密通訊。The client uses the furnished certificate for encrypted communication with the server during the secure session that follows the TLS handshake.

Kestrel 透過 ServerCertificateSelector 回呼來支援 SNI。Kestrel supports SNI via the ServerCertificateSelector callback. 回呼會針對每個連線叫用一次,允許應用程式檢查主機名稱並選取適當的憑證。The callback is invoked once per connection to allow the app to inspect the host name and select the appropriate certificate.

SNI 支援需要:SNI support requires:

  • 在目標 Framework netcoreapp2.1 上執行。Running on target framework netcoreapp2.1. netcoreapp2.0net461 上,會叫用回呼,但 name 一律為 nullOn netcoreapp2.0 and net461, the callback is invoked but the name is always null. 如果用戶端不在 TLS 信號交換中提供主機名稱參數,則 name 也是 nullThe name is also null if the client doesn't provide the host name parameter in the TLS handshake.
  • 所有網站都在相同的 Kestrel 執行個體上執行。All websites run on the same Kestrel instance. 在不使用反向 Proxy 的情況下,Kestrel 不支援跨多個執行個體共用 IP 位址和連接埠。Kestrel doesn't support sharing an IP address and port across multiple instances without a reverse proxy.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.ListenAnyIP(5005, listenOptions =>
            {
                listenOptions.UseHttps(httpsOptions =>
                {
                    var localhostCert = CertificateLoader.LoadFromStoreCert(
                        "localhost", "My", StoreLocation.CurrentUser, 
                        allowInvalid: true);
                    var exampleCert = CertificateLoader.LoadFromStoreCert(
                        "example.com", "My", StoreLocation.CurrentUser, 
                        allowInvalid: true);
                    var subExampleCert = CertificateLoader.LoadFromStoreCert(
                        "sub.example.com", "My", StoreLocation.CurrentUser, 
                        allowInvalid: true);
                    var certs = new Dictionary<string, X509Certificate2>(
                        StringComparer.OrdinalIgnoreCase);
                    certs["localhost"] = localhostCert;
                    certs["example.com"] = exampleCert;
                    certs["sub.example.com"] = subExampleCert;

                    httpsOptions.ServerCertificateSelector = (connectionContext, name) =>
                    {
                        if (name != null && certs.TryGetValue(name, out var cert))
                        {
                            return cert;
                        }

                        return exampleCert;
                    };
                });
            });
        });
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel((context, options) =>
        {
            options.ListenAnyIP(5005, listenOptions =>
            {
                listenOptions.UseHttps(httpsOptions =>
                {
                    var localhostCert = CertificateLoader.LoadFromStoreCert(
                        "localhost", "My", StoreLocation.CurrentUser, 
                        allowInvalid: true);
                    var exampleCert = CertificateLoader.LoadFromStoreCert(
                        "example.com", "My", StoreLocation.CurrentUser, 
                        allowInvalid: true);
                    var subExampleCert = CertificateLoader.LoadFromStoreCert(
                        "sub.example.com", "My", StoreLocation.CurrentUser, 
                        allowInvalid: true);
                    var certs = new Dictionary<string, X509Certificate2>(
                        StringComparer.OrdinalIgnoreCase);
                    certs["localhost"] = localhostCert;
                    certs["example.com"] = exampleCert;
                    certs["sub.example.com"] = subExampleCert;

                    httpsOptions.ServerCertificateSelector = (connectionContext, name) =>
                    {
                        if (name != null && certs.TryGetValue(name, out var cert))
                        {
                            return cert;
                        }

                        return exampleCert;
                    };
                });
            });
        })
        .Build();

繫結至 TCP 通訊端Bind to a TCP socket

Listen 方法會繫結至 TCP 通訊端,而選項 Lambda 則會允許 X.509 憑證設定:The Listen method binds to a TCP socket, and an options lambda permits X.509 certificate configuration:

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

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Listen(IPAddress.Loopback, 5000);
            options.Listen(IPAddress.Loopback, 5001, listenOptions =>
            {
                listenOptions.UseHttps("testCert.pfx", "testPassword");
            });
        });
public static void Main(string[] args)
{
    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(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");
            });
        });
public static void Main(string[] args)
{
    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(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");
            });
        });

此範例使用 ListenOptions來為端點設定 HTTPS。The example configures HTTPS for an endpoint with ListenOptions. 若要設定特定端點的其他 Kestrel 設定,請使用相同的 API。Use the same API to configure other Kestrel settings for specific endpoints.

在 Windows 中,可使用 New-SelfSignedCertificate PowerShell cmdlet 建立自我簽署的憑證。On Windows, self-signed certificates can be created using the New-SelfSignedCertificate PowerShell cmdlet. 如需不支援的範例,請參閱 UpdateIISExpressSSLForChrome.ps1 (英文)。For an unsupported example, see UpdateIISExpressSSLForChrome.ps1.

在 macOS、Linux 和 Windows 上,可以使用 OpenSSL (英文) 建立憑證。On macOS, Linux, and Windows, certificates can be created using OpenSSL.

繫結至 Unix 通訊端Bind to a Unix socket

請使用 ListenUnixSocket 在 Unix 通訊端上進行接聽以改善 Nginx 的效能,如此範例所示:Listen on a Unix socket with ListenUnixSocket for improved performance with Nginx, as shown in this example:

.ConfigureKestrel((context, options) =>
{
    options.ListenUnixSocket("/tmp/kestrel-test.sock");
    options.ListenUnixSocket("/tmp/kestrel-test.sock", listenOptions =>
    {
        listenOptions.UseHttps("testCert.pfx", "testpassword");
    });
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.ListenUnixSocket("/tmp/kestrel-test.sock");
            options.ListenUnixSocket("/tmp/kestrel-test.sock", listenOptions =>
            {
                listenOptions.UseHttps("testCert.pfx", "testpassword");
            });
        });

連接埠 0Port 0

指定連接埠號碼 0 時,Kestrel 會動態繫結至可用的連接埠。When the port number 0 is specified, Kestrel dynamically binds to an available port. 下列範例示範如何判斷 Kestrel 在執行階段實際上繫結至哪一個連接埠:The following example shows how to determine which port Kestrel actually bound at runtime:

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

    app.UseStaticFiles();

    app.Run(async (context) =>
    {
        context.Response.ContentType = "text/html";
        await context.Response
            .WriteAsync("<!DOCTYPE html><html lang=\"en\"><head>" +
                "<title></title></head><body><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>");
    });
}

當應用程式執行時,主控台視窗輸出會指出可以連線到應用程式的動態連接埠:When the app is run, the console window output indicates the dynamic port where the app can be reached:

Listening on the following addresses: http://127.0.0.1:48508

限制Limitations

使用下列方法來設定端點:Configure endpoints with the following approaches:

  • UseUrls
  • --urls 命令列引數--urls command-line argument
  • urls 主機組態索引鍵urls host configuration key
  • ASPNETCORE_URLS 環境變數ASPNETCORE_URLS environment variable

要讓程式碼使用 Kestrel 以外的伺服器,這些方法會很有用。These methods are useful for making code work with servers other than Kestrel. 不過,請注意下列限制:However, be aware of the following limitations:

  • HTTPS 無法與這些方法搭配使用,除非在 HTTPS 端點設定中提供預設憑證 (例如,使用 KestrelServerOptions 設定或設定檔,如本主題稍早所示)。HTTPS can't be used with these approaches unless a default certificate is provided in the HTTPS endpoint configuration (for example, using KestrelServerOptions configuration or a configuration file as shown earlier in this topic).
  • 當同時使用 ListenUseUrls 方法時,Listen 端點會覆寫 UseUrls 端點。When both the Listen and UseUrls approaches are used simultaneously, the Listen endpoints override the UseUrls endpoints.

IIS 端點設定IIS endpoint configuration

使用 IIS 時,IIS 覆寫繫結的 URL 繫結是由 ListenUseUrls 設定。When using IIS, the URL bindings for IIS override bindings are set by either Listen or UseUrls. 如需詳細資訊,請參閱 ASP.NET Core 模組主題。For more information, see the ASP.NET Core Module topic.

ListenOptions.ProtocolsListenOptions.Protocols

Protocols 屬性會建立在連線端點上或針對伺服器啟用的 HTTP 通訊協定 (HttpProtocols)。The Protocols property establishes the HTTP protocols (HttpProtocols) enabled on a connection endpoint or for the server. HttpProtocols 列舉中指派一個值給 Protocols 屬性。Assign a value to the Protocols property from the HttpProtocols enum.

HttpProtocols 列舉值HttpProtocols enum value 允許的連線通訊協定Connection protocol permitted
Http1 僅限 HTTP/1.1。HTTP/1.1 only. 可在具有或沒有 TLS 的情況下使用。Can be used with or without TLS.
Http2 僅限 HTTP/2。HTTP/2 only. 主要在具有 TLS 的情況下使用。Primarily used with TLS. 只有在用戶端支援先備知識模式時,才可以在沒有 TLS 的情況下使用。May be used without TLS only if the client supports a Prior Knowledge mode.
Http1AndHttp2 HTTP/1.1 和 HTTP/2。HTTP/1.1 and HTTP/2. 需要 TLS 和 Application-Layer Protocol Negotiation (ALPN) 連線才能交涉 HTTP/2;否則,連線預設為 HTTP/1.1。Requires a TLS and Application-Layer Protocol Negotiation (ALPN) connection to negotiate HTTP/2; otherwise, the connection defaults to HTTP/1.1.

預設通訊協定為 HTTP/1.1。The default protocol is HTTP/1.1.

HTTP/2 的 TLS 限制:TLS restrictions for HTTP/2:

  • TLS 1.2 版或更新版本TLS version 1.2 or later
  • 已停用重新交涉Renegotiation disabled
  • 已停用壓縮Compression disabled
  • 暫時金鑰交換大小下限:Minimum ephemeral key exchange sizes:
    • 橢圓曲線 Diffie-Hellman (ECDHE) [RFC4492] – 最小 224 個位元Elliptic curve Diffie-Hellman (ECDHE) [RFC4492] – 224 bits minimum
    • 有限欄位 Diffie-Hellman (DHE) [TLS12] – 最小 2048 個位元Finite field Diffie-Hellman (DHE) [TLS12] – 2048 bits minimum
  • 加密套件未列於封鎖清單中Cipher suite not blacklisted

預設支援 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 [TLS-ECDHE] 與 P-256 橢圓曲線 [FIPS186]。TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 [TLS-ECDHE] with the P-256 elliptic curve [FIPS186] is supported by default.

下列範例會允許連接埠 8000 上的 HTTP/1.1 和 HTTP/2 連線。The following example permits HTTP/1.1 and HTTP/2 connections on port 8000. 這些連線使用提供的憑證受到 TLS 保護:Connections are secured by TLS with a supplied certificate:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Listen(IPAddress.Any, 8000, listenOptions =>
            {
                listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                listenOptions.UseHttps("testCert.pfx", "testPassword");
            });
        });

選擇性地建立 IConnectionAdapter 實作,針對每個連線來篩選特定加密的 TLS 交握:Optionally create an IConnectionAdapter implementation to filter TLS handshakes on a per-connection basis for specific ciphers:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            options.Listen(IPAddress.Any, 8000, listenOptions =>
            {
                listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                listenOptions.UseHttps("testCert.pfx", "testPassword");
                listenOptions.ConnectionAdapters.Add(new TlsFilterAdapter());
            });
        });
private class TlsFilterAdapter : IConnectionAdapter
{
    public bool IsHttps => false;

    public Task<IAdaptedConnection> OnConnectionAsync(ConnectionAdapterContext context)
    {
        var tlsFeature = context.Features.Get<ITlsHandshakeFeature>();

        // Throw NotSupportedException for any cipher algorithm that you don't 
        // wish to support. Alternatively, define and compare 
        // ITlsHandshakeFeature.CipherAlgorithm to a list of acceptable cipher 
        // suites.
        //
        // A ITlsHandshakeFeature.CipherAlgorithm of CipherAlgorithmType.Null 
        // indicates that no cipher algorithm supported by Kestrel matches the 
        // requested algorithm(s).
        if (tlsFeature.CipherAlgorithm == CipherAlgorithmType.Null)
        {
            throw new NotSupportedException("Prohibited cipher: " + tlsFeature.CipherAlgorithm);
        }

        return Task.FromResult<IAdaptedConnection>(new AdaptedConnection(context.ConnectionStream));
    }

    private class AdaptedConnection : IAdaptedConnection
    {
        public AdaptedConnection(Stream adaptedStream)
        {
            ConnectionStream = adaptedStream;
        }

        public Stream ConnectionStream { get; }

        public void Dispose()
        {
        }
    }
}

從設定進行通訊協定設定 Set the protocol from configuration

CreateDefaultBuilder 預設會呼叫 serverOptions.Configure(context.Configuration.GetSection("Kestrel")) 以載入 Kestrel 設定。CreateDefaultBuilder calls serverOptions.Configure(context.Configuration.GetSection("Kestrel")) by default to load Kestrel configuration.

在下列 appsettings.json 範例中,會為 Kestrel 的所有端點建立預設連線通訊協定 (HTTP/1.1 和 HTTP/2):In the following appsettings.json example, a default connection protocol (HTTP/1.1 and HTTP/2) is established for all of Kestrel's endpoints:

{
  "Kestrel": {
    "EndPointDefaults": {
      "Protocols": "Http1AndHttp2"
    }
  }
}

下列設定檔範例會為特定端點建立連線通訊協定:The following configuration file example establishes a connection protocol for a specific endpoint:

{
  "Kestrel": {
    "EndPoints": {
      "HttpsDefaultCert": {
        "Url": "https://localhost:5001",
        "Protocols": "Http1AndHttp2"
      }
    }
  }
}

程式碼中指定的通訊協定會覆寫設定所設定的值。Protocols specified in code override values set by configuration.

傳輸組態Transport configuration

隨著 ASP.NET Core 2.1 的發行,Kestrel 的預設傳輸不再根據 Libuv,而是改為根據受控通訊端。With the release of ASP.NET Core 2.1, Kestrel's default transport is no longer based on Libuv but instead based on managed sockets. 對於升級到 2.1 且會呼叫 UseLibuv 並相依於下列任一套件的 ASP.NET Core 2.0 應用程式來說,這是一項中斷性變更:This is a breaking change for ASP.NET Core 2.0 apps upgrading to 2.1 that call UseLibuv and depend on either of the following packages:

對於使用 Microsoft.AspNetCore.App 中繼套件且需要使用 Libuv 的 ASP.NET Core 2.1 或更新版本專案:For ASP.NET Core 2.1 or later projects that use the Microsoft.AspNetCore.App metapackage and require the use of Libuv:

  • Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv 套件的相依性新增至應用程式的專案檔中:Add a dependency for the Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv package to the app's project file:

    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv" 
                      Version="<LATEST_VERSION>" />
    
  • 呼叫 UseLibuvCall UseLibuv:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseLibuv()
                .UseStartup<Startup>();
    }
    

URL 前置詞URL prefixes

使用 UseUrls--urls 命令列引數、urls 主機組態索引鍵或 ASPNETCORE_URLS 環境變數時,URL 前置詞可以採用下列任一格式。When using UseUrls, --urls command-line argument, urls host configuration key, or ASPNETCORE_URLS environment variable, the URL prefixes can be in any of the following formats.

只有 HTTP URL 前置詞有效。Only HTTP URL prefixes are valid. 使用 UseUrls 來設定 URL 繫結時,Kestrel 不支援 HTTPS。Kestrel doesn't support HTTPS when configuring URL bindings using UseUrls.

  • IPv4 位址與連接埠號碼IPv4 address with port number

    http://65.55.39.10:80/
    

    0.0.0.0 是繫結至所有 IPv4 位址的特殊情況。0.0.0.0 is a special case that binds to all IPv4 addresses.

  • IPv6 位址與連接埠號碼IPv6 address with port number

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

    [::] 是相當於 IPv4 0.0.0.0 的 IPv6 對等項目。[::] is the IPv6 equivalent of IPv4 0.0.0.0.

  • 主機名稱與連接埠號碼Host name with port number

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

    主機名稱 *+ 並不特殊。Host names, *, and +, aren't special. 無法辨識為有效 IP 位址或 localhost 的任何項目,都會繫結至所有 IPv4 和 IPv6 IP。Anything not recognized as a valid IP address or localhost binds to all IPv4 and IPv6 IPs. 若要在相同連接埠上將不同的主機名稱繫結至不同的 ASP.NET Core 應用程式,請使用 HTTP.sys 或反向 Proxy 伺服器 (例如 IIS、Nginx 或 Apache)。To bind different host names to different ASP.NET Core apps on the same port, use HTTP.sys or a reverse proxy server, such as IIS, Nginx, or Apache.

    警告

    裝載於反向 Proxy 組態需要主機篩選Hosting in a reverse proxy configuration requires host filtering.

  • 主機 localhost 名稱與連接埠號碼,或回送 IP 與連接埠號碼Host localhost name with port number or loopback IP with port number

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

    如果指定 localhost,Kestrel 會嘗試同時繫結至 IPv4 和 IPv6 回送介面。When localhost is specified, Kestrel attempts to bind to both IPv4 and IPv6 loopback interfaces. 如果所要求的連接埠在任一個回送介面上由另一個服務使用,則 Kestrel 無法啟動。If the requested port is in use by another service on either loopback interface, Kestrel fails to start. 如果任一回送介面由於任何其他原因 (最常見的原因是不支援 IPv6) 無法使用,Kestrel 就會記錄警告。If either loopback interface is unavailable for any other reason (most commonly because IPv6 isn't supported), Kestrel logs a warning.

主機篩選Host filtering

雖然 Kestrel 根據前置詞來支援組態,例如 http://example.com:5000,Kestrel 大多會忽略主機名稱。While Kestrel supports configuration based on prefixes such as http://example.com:5000, Kestrel largely ignores the host name. 主機 localhost 是特殊情況,用來繫結到回送位址。Host localhost is a special case used for binding to loopback addresses. 任何非明確 IP 位址的主機,會繫結至所有公用 IP 位址。Any host other than an explicit IP address binds to all public IP addresses. Host 標頭未驗證。Host headers aren't validated.

因應措施是使用主機篩選中介軟體。As a workaround, use Host Filtering Middleware. 主機篩選中介軟體係由 Microsoft.AspNetCore.HostFiltering 套件提供,隨附於 Microsoft.AspNetCore.App 中繼套件 (ASP.NET Core 2.1 或更新版本)。Host Filtering Middleware is provided by the Microsoft.AspNetCore.HostFiltering package, which is included in the Microsoft.AspNetCore.App metapackage (ASP.NET Core 2.1 or later). 中介軟體是由 CreateDefaultBuilder 所新增,它會呼叫 AddHostFilteringThe middleware is added by CreateDefaultBuilder, which calls AddHostFiltering:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

預設停用主機篩選中介軟體。Host Filtering Middleware is disabled by default. 若要啓用中介軟體,請在 appsettings.json/appsettings.<環境名稱>.json 中定義 AllowedHosts 索引鍵。To enable the middleware, define an AllowedHosts key in appsettings.json/appsettings.<EnvironmentName>.json. 此值是以分號分隔的主機名稱清單,不含連接埠號碼:The value is a semicolon-delimited list of host names without port numbers:

appsettings.jsonappsettings.json:

{
  "AllowedHosts": "example.com;localhost"
}

注意

轉送的標頭中介軟體也有 AllowedHosts 選項。Forwarded Headers Middleware also has an AllowedHosts option. 在不同的案例中,轉送標頭中介軟體和主機篩選中介軟體有類似的功能。Forwarded Headers Middleware and Host Filtering Middleware have similar functionality for different scenarios. 當不保留 Host 標頭,卻使用反向 Proxy 伺服器或負載平衡器轉送要求時,可使用轉送標頭中介軟體設定 AllowedHostsSetting AllowedHosts with Forwarded Headers Middleware is appropriate when the Host header isn't preserved while forwarding requests with a reverse proxy server or load balancer. 當使用 Kestrel 作為公眾對應 Edge Server,或直接轉送 Host 標頭時,可使用主機篩選中介軟體設定 AllowedHostsSetting AllowedHosts with Host Filtering Middleware is appropriate when Kestrel is used as a public-facing edge server or when the Host header is directly forwarded.

如需轉送標頭中介軟體的詳細資訊,請參閱設定 ASP.NET Core 以與 Proxy 伺服器和負載平衡器搭配運作For more information on Forwarded Headers Middleware, see 設定 ASP.NET Core 以與 Proxy 伺服器和負載平衡器搭配運作.

其他資源Additional resources