ASP.NET Core への Kestrel Web サーバーの実装Kestrel web server implementation in ASP.NET Core
作成者: Tom Dykstra、Chris Ross、Stephen Halter、Luke LathamBy Tom Dykstra, Chris Ross, Stephen Halter, and Luke Latham
Kestrel は、ASP.NET Core 向けのクロスプラットフォーム Web サーバーです。Kestrel is a cross-platform web server for ASP.NET Core. Kestrel は、ASP.NET Core のプロジェクト テンプレートに既定で含まれる Web サーバーです。Kestrel is the web server that's included by default in ASP.NET Core project templates.
Kestrel では、次のシナリオがサポートされます。Kestrel supports the following scenarios:
- HTTPSHTTPS
- Websocket を有効にするために使用される非透過的なアップグレードOpaque upgrade used to enable WebSockets
- Nginx の背後にある高パフォーマンスの UNIX ソケットUnix sockets for high performance behind Nginx
- HTTP/2 (macOS の場合を除く†)HTTP/2 (except on macOS†)
†将来のリリースでは HTTP/2 が macOS 上でサポートされるようになります。†HTTP/2 will be supported on macOS in a future release.
kestrel は、.NET Core がサポートするすべてのプラットフォームおよびバージョンでサポートされます。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
Http/2 は、次の基本要件が満たされている場合に、ASP.NET Core アプリで使用できます。HTTP/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‡
- OpenSSL 1.0.2 以降を使用した Linux (Ubuntu 16.04 以降など)Linux with OpenSSL 1.0.2 or later (for example, Ubuntu 16.04 or later)
- ターゲット フレームワーク: .NET Core 2.2 以降Target framework: .NET Core 2.2 or later
- アプリケーション レイヤー プロトコル ネゴシエーション (ALPN) 接続Application-Layer Protocol Negotiation (ALPN) connection
- TLS 1.2 以降の接続TLS 1.2 or later connection
†将来のリリースでは HTTP/2 が macOS 上でサポートされるようになります。†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. TLS 接続をセキュリティで保護するためには、楕円曲線デジタル署名アルゴリズム (ECDSA) を使用して生成した証明書が必要になる場合があります。A certificate generated using an Elliptic Curve Digital Signature Algorithm (ECDSA) may be required to secure TLS connections.
Http/2 接続が確立されると、HttpRequest.Protocol が HTTP/2
を報告します。If an HTTP/2 connection is established, HttpRequest.Protocol reports HTTP/2
.
Http/2 は既定では無効になっています。HTTP/2 is disabled by default. 構成の詳細については、「Kestrel オプション」セクションと「ListenOptions.Protocols」セクションを参照してください。For more information on configuration, see the Kestrel options and ListenOptions.Protocols sections.
Kestrel とリバース プロキシを使用するタイミングWhen to use Kestrel with a reverse proxy
Kestrel を単独で使用することも、インターネット インフォメーション サービス (IIS)、Nginx、Apache などのリバース プロキシ サーバーと併用することもできます。Kestrel can be used by itself or with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. リバース プロキシ サーバーはネットワークから HTTP 要求を受け取り、これを Kestrel に転送します。A reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.
エッジ (インターネットに接続する) Web サーバーとして使用される Kestrel:Kestrel used as an edge (Internet-facing) web server:
リバース プロキシ構成で使用される Kestrel:Kestrel used in a reverse proxy configuration:
いずれの構成でも、リバース プロキシ サーバーの有無に関わらず、ホスティング構成がサポートされています。Either configuration, with or without a reverse proxy server, is a supported hosting configuration.
リバース プロキシ サーバーのないエッジ サーバーとして使用される Kestrel は、複数のプロセス間で同じ 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. ポートを共有できるリバース プロキシは、一意の IP とポート上の Kestrel に要求を転送することができます。A reverse proxy that can share ports has the ability to forward requests to Kestrel on a unique IP and port.
リバース プロキシ サーバーが必要ない場合であっても、リバース プロキシ サーバーを使用すると次のような利点があります。Even if a reverse proxy server isn't required, using a reverse proxy server might be a good choice.
リバース プロキシ: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. リバース プロキシ サーバーのみで X.509 証明書が必要です。このサーバーでは、プレーンな HTTP を使用して内部ネットワーク上のアプリのサーバーと通信することができます。Only the reverse proxy server requires an X.509 certificate, and that server can communicate with the app's servers on the internal network using plain HTTP.
警告
リバース プロキシ構成でのホストにはホストのフィルター処理が必要です。Hosting in a reverse proxy configuration requires host filtering.
ASP.NET Core アプリでの KestrelKestrel in ASP.NET Core apps
ASP.NET Core プロジェクト テンプレートは既定では Kestrel を使用します。ASP.NET Core project templates use Kestrel by default. Program.cs では、ConfigureWebHostDefaults メソッドにより UseKestrel が呼び出されます。In Program.cs, the ConfigureWebHostDefaults method calls UseKestrel:
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ホストのビルトに関する詳細については、「.NET での汎用ホスト」の「ホストを設定する」と「既定の builder 設定」セクションを参照してください。For more information on building the host, see the Set up a host and Default builder settings sections of .NET での汎用ホスト.
ConfigureWebHostDefaults
を呼び出した後に追加の構成を指定するには、ConfigureKestrel
を使用します。To provide additional configuration after calling ConfigureWebHostDefaults
, use ConfigureKestrel
:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
// Set properties and call methods on options
})
.UseStartup<Startup>();
});
Kestrel オプションKestrel options
Kestrel Web サーバーには、インターネットに接続する展開で特に有効な制約構成オプションがいくつかあります。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;
次の例の C# コード内で構成されている Kestrel オプションは、構成プロバイダーを使って設定することもできます。Kestrel options, which are configured in C# code in the following examples, can also be set using a configuration provider. たとえば、ファイル構成プロバイダーによって、appsettings.json または "appsettings.{環境}.json" ファイルから Kestrel 構成を読み込むことができます。For example, the File Configuration Provider can load Kestrel configuration from an appsettings.json or appsettings.{Environment}.json file:
{
"Kestrel": {
"Limits": {
"MaxConcurrentConnections": 100,
"MaxConcurrentUpgradedConnections": 100
},
"DisableStringReuse": true
}
}
次の方法のいずれかを使用します。Use one of the following approaches:
Startup.ConfigureServices
で Kestrel を構成する。Configure Kestrel inStartup.ConfigureServices
:IConfiguration
のインスタンスをStartup
クラスに挿入します。Inject an instance ofIConfiguration
into theStartup
class. 以下の例では、挿入された構成がConfiguration
プロパティに割り当てられることを前提としています。The following example assumes that the injected configuration is assigned to theConfiguration
property.Startup.ConfigureServices
で、構成のKestrel
セクションを Kestrel の構成に読み込みます。InStartup.ConfigureServices
, load theKestrel
section of configuration into Kestrel's configuration.// using Microsoft.Extensions.Configuration public void ConfigureServices(IServiceCollection services) { services.Configure<KestrelServerOptions>( Configuration.GetSection("Kestrel")); }
ホストのビルド時に Kestrel を構成する。Configure Kestrel when building the host:
Program.cs で、構成の
Kestrel
セクションを Kestrel の構成に読み込みます。In Program.cs, load theKestrel
section of configuration into Kestrel's configuration:// using Microsoft.Extensions.DependencyInjection; public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure<KestrelServerOptions>( context.Configuration.GetSection("Kestrel")); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
上記の方法はいずれも、任意の構成プロバイダーで使用できます。Both of the preceding approaches work with any configuration provider.
Keep-Alive タイムアウトKeep-alive timeout
Keep-Alive タイムアウトを取得するか、設定します。Gets or sets the keep-alive timeout. 既定値は 2 分です。Defaults to 2 minutes.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
})
クライアントの最大接続数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:
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
})
HTTP または HTTPS から別のプロトコルにアップグレードされた接続については別個の制限があります (WebSockets 要求に関する制限など)。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.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
})
接続の最大数は既定では無制限 (null) です。The maximum number of connections is unlimited (null) by default.
要求本文の最大サイズMaximum request body size
既定の要求本文の最大サイズは、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:
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
})
ミドルウェア内の特定の要求で設定をオーバーライドします。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 the app configures the limit on a request after the app has started to read the request. MaxRequestBodySize
プロパティが読み取り専用状態にある (制限を構成するには遅すぎる) かどうかを示す IsReadOnly
プロパティがあります。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 Module の背後でアプリがアウト プロセスで実行されるとき、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. 要求制限と応答制限を設定するコードは、プロパティ名およびインターフェイス名に RequestBody
または Response
が使用されることを除けば同じです。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:
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
})
ミドルウェアでは要求ごとに最小レート制限をオーバーライドします。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));
}
前のサンプルで参照した IHttpMinResponseDataRateFeature は、HTTP/2 要求の HttpContext.Features
には存在しません。これは、プロトコルで要求の多重化に対応するために、要求ごとのレート制限の変更が、HTTP/2 で一般的にサポートされていないからです。The IHttpMinResponseDataRateFeature referenced in the prior sample is not present in HttpContext.Features
for HTTP/2 requests because modifying rate limits on a per-request basis is generally not supported for HTTP/2 due to the protocol's support for request multiplexing. ただし、IHttpMinRequestBodyDataRateFeature は引き続き現在の HTTP/2 要求の HttpContext.Features
です。これは、HTTP/2 要求に対してであっても、IHttpMinRequestBodyDataRateFeature.MinDataRate
を null
に設定すれば、読み取りのレート制限を要求ごとに "すべて無効" にできるためです。However, the IHttpMinRequestBodyDataRateFeature is still present HttpContext.Features
for HTTP/2 requests, because the read rate limit can still be disabled entirely on a per-request basis by setting IHttpMinRequestBodyDataRateFeature.MinDataRate
to null
even for an HTTP/2 request. IHttpMinRequestBodyDataRateFeature.MinDataRate
を読み取ろうとしたり、null
以外の値に設定しようとしたりすると、HTTP/2 要求を指定した NotSupportedException
がスローされます。Attempting to read IHttpMinRequestBodyDataRateFeature.MinDataRate
or attempting to set it to a value other than null
will result in a NotSupportedException
being thrown given an HTTP/2 request.
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
サーバーで要求ヘッダーの受信にかかる時間の最大値を取得または設定します。Gets or sets the maximum amount of time the server spends receiving request headers. 既定値は 30 秒です。Defaults to 30 seconds.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
})
接続ごとの最大ストリームMaximum streams per connection
HTTP/2 接続ごとの同時要求ストリームの数は、Http2.MaxStreamsPerConnection
によって制限されます。Http2.MaxStreamsPerConnection
limits the number of concurrent request streams per HTTP/2 connection. 余分なストリームは拒否されます。Excess streams are refused.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.Http2.MaxStreamsPerConnection = 100;
});
既定値は 100 です。The default value is 100.
ヘッダー テーブルのサイズHeader table size
HTTP/2 接続では、HTTP ヘッダーは HPACK デコーダーによって圧縮解除されます。The HPACK decoder decompresses HTTP headers for HTTP/2 connections. HPACK デコーダーが使用するヘッダー圧縮テーブルのサイズは Http2.HeaderTableSize
によって制限されます。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).
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.Http2.HeaderTableSize = 4096;
});
既定値は 4096 です。The default value is 4096.
最大フレーム サイズMaximum frame size
Http2.MaxFrameSize
は、サーバーによって受信または送信された HTTP/2 接続フレーム ペイロードの最大許容サイズを示しています。Http2.MaxFrameSize
indicates the maximum allowed size of an HTTP/2 connection frame payload received or sent by the server. 値はオクテット単位で指定し、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).
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.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 in their compressed and uncompressed representations. ゼロ (0) より大きい値である必要があります。The value must be greater than zero (0).
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.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).
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.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.InitialConnectionWindowSize
による制限も受けます。Requests are also limited by Http2.InitialConnectionWindowSize
. この値は 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).
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.Http2.InitialStreamWindowSize = 98304;
});
既定値は 96 KB (98,304) です。The default value is 96 KB (98,304).
同期 IOSynchronous IO
AllowSynchronousIO を使うと、要求と応答に対して同期 IO を許可するかどうかを制御できます。AllowSynchronousIO controls whether synchronous IO is allowed for the request and response. 既定値は false
です。The default value is false
.
警告
ブロッキング同期 IO 操作の回数が多いと、スレッド プールの不足を招き、アプリが応答しなくなる可能性があります。A large number of blocking synchronous IO operations can lead to thread pool starvation, which makes the app unresponsive. 非同期 IO をサポートしていないライブラリを使用する場合にのみ AllowSynchronousIO
を有効にしてください。Only enable AllowSynchronousIO
when using a library that doesn't support asynchronous IO.
同期 IO を有効にする例を次に示します。The following example enables synchronous IO:
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.AllowSynchronousIO = true;
})
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.
これらの方法を使うと、1 つまたは複数の 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:
- .NET Core SDK がインストールされるとき。When the .NET Core SDK is installed.
- 証明書を作成するには dev-certs ツールを使います。The dev-certs tool is used to create a certificate.
一部のブラウザーでは、ローカル開発証明書を信頼するには、明示的にアクセス許可を付与する必要があります。Some browsers require granting explicit permission to trust the local development certificate.
プロジェクト テンプレートでは、アプリを HTTPS で実行するように既定で構成され、HTTPS のリダイレクトと HSTS のサポートが含まれます。Project templates configure apps to run on HTTPS by default and include HTTPS redirection and HSTS support.
KestrelServerOptions で Listen または ListenUnixSocket メソッドを呼び出して、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).
KestrelServerOptions
構成:KestrelServerOptions
configuration:
ConfigureEndpointDefaults(Action<ListenOptions>)ConfigureEndpointDefaults(Action<ListenOptions>)
指定した各エンドポイントに対して実行するように、構成の Action
を指定します。Specifies a configuration Action
to run for each specified endpoint. ConfigureEndpointDefaults
を複数回呼び出すと、前の Action
が最後に指定した Action
で置き換えられます。Calling ConfigureEndpointDefaults
multiple times replaces prior Action
s with the last Action
specified.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureEndpointDefaults(listenOptions =>
{
// Configure endpoint defaults
});
});
注意
ConfigureEndpointDefaults を呼び出す前に Listen を呼び出すことで作成されるエンドポイントには既定値が適用されません。Endpoints created by calling Listen before calling ConfigureEndpointDefaults won't have the defaults applied.
ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)
各 HTTPS エンドポイントに対して実行するように、構成の Action
を指定します。Specifies a configuration Action
to run for each HTTPS endpoint. ConfigureHttpsDefaults
を複数回呼び出すと、前の Action
が最後に指定した Action
で置き換えられます。Calling ConfigureHttpsDefaults
multiple times replaces prior Action
s with the last Action
specified.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
// certificate is an X509Certificate2
listenOptions.ServerCertificate = certificate;
});
});
注意
ConfigureHttpsDefaults を呼び出す前に Listen を呼び出すことで作成されるエンドポイントには既定値が適用されません。Endpoints created by calling Listen before calling ConfigureHttpsDefaults won't have the defaults applied.
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
HTTPS を使用するように Kestrel を構成します。Configure Kestrel to use HTTPS.
ListenOptions.UseHttps
拡張機能:ListenOptions.UseHttps
extensions:
UseHttps
– 既定の証明書で HTTPS を使うように Kestrel を構成します。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
は、HttpsConnectionAdapterOptions
を構成するためのAction
です。configureOptions
is anAction
to configure theHttpsConnectionAdapterOptions
.ListenOptions
を返します。Returns theListenOptions
.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:5000
と https://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
は既定で Configure(context.Configuration.GetSection("Kestrel"))
を呼び出して Kestrel の構成を読み込みます。CreateDefaultBuilder
calls 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 totrue
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>"
}
}
}
}
証明書ノードの Path と 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. たとえば、
HTTPS
とHttps
は有効です。For example,HTTPS
andHttps
are valid. Url
パラメーターは、エンドポイントごとに必要です。TheUrl
parameter is required for each endpoint. このパラメーターの形式は、1 つの値に制限されることを除き、最上位レベルのUrls
構成パラメーターと同じです。The format for this parameter is the same as the top-levelUrls
configuration parameter except that it's limited to a single value.- これらのエンドポイントは、最上位レベルの
Urls
構成での定義に追加されるのではなく、それを置き換えます。These endpoints replace those defined in the top-levelUrls
configuration rather than adding to them. コードでListen
を使用して定義されているエンドポイントは、構成セクションで定義されているエンドポイントに累積されます。Endpoints defined in code viaListen
are cumulative with the endpoints defined in the configuration section. Certificate
セクションは省略可能です。TheCertificate
section is optional.Certificate
セクションを指定しないと、前述のシナリオで定義した既定値が使用されます。If theCertificate
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
セクションは、Path–Password 証明書と Subject–Store 証明書の両方をサポートします。TheCertificate
section supports both Path–Password and Subject–Store 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("{SECTION}"))
が.Endpoint(string name, listenOptions => { })
メソッドで返すKestrelConfigurationLoader
を使用して、構成されているエンドポイントの設定を補足できます。options.Configure(context.Configuration.GetSection("{SECTION}"))
returns aKestrelConfigurationLoader
with an.Endpoint(string name, listenOptions => { })
method that can be used to supplement a configured endpoint's settings:
webBuilder.UseKestrel((context, serverOptions) =>
{
serverOptions.Configure(context.Configuration.GetSection("Kestrel"))
.Endpoint("HTTPS", listenOptions =>
{
listenOptions.HttpsOptions.SslProtocols = SslProtocols.Tls12;
});
});
KestrelServerOptions.ConfigurationLoader
に直接アクセスして、既存のローダー (CreateDefaultBuilder によって提供されるものなど) の反復を維持することができます。KestrelServerOptions.ConfigurationLoader
can be directly accessed to continue iterating on the existing loader, such as the one provided by CreateDefaultBuilder.
- カスタム設定を読み取ることができるように、各エンドポイントの構成セクションを
Endpoint
メソッドのオプションで使用できます。The configuration section for each endpoint is available on the options in theEndpoint
method so that custom settings may be read. - 別のセクションで
options.Configure(context.Configuration.GetSection("{SECTION}"))
を再び呼び出すことにより、複数の構成を読み込むことができます。Multiple configurations may be loaded by callingoptions.Configure(context.Configuration.GetSection("{SECTION}"))
again with another section. 前のインスタンスでLoad
を明示的に呼び出していない限り、最後の構成のみが使用されます。Only the last configuration is used, unlessLoad
is explicitly called on prior instances. 既定の構成セクションを置き換えることができるように、メタパッケージはLoad
を呼び出しません。The metapackage doesn't callLoad
so that its default configuration section may be replaced. KestrelConfigurationLoader
はミラー、KestrelServerOptions
から API のListen
ファミリをEndpoint
オーバーロードとしてミラーリングするので、コードと構成のエンドポイントを同じ場所で構成できます。KestrelConfigurationLoader
mirrors theListen
family of APIs fromKestrelServerOptions
asEndpoint
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
ConfigureEndpointDefaults
およびConfigureHttpsDefaults
を使用して、ListenOptions
および HttpsConnectionAdapterOptions
の既定の設定を変更できます (前のシナリオで指定した既定の証明書のオーバーライドなど)。ConfigureEndpointDefaults
and ConfigureHttpsDefaults
can be used to change default settings for ListenOptions
and HttpsConnectionAdapterOptions
, including overriding the default certificate specified in the prior scenario. エンドポイントを構成する前に、ConfigureEndpointDefaults
および ConfigureHttpsDefaults
を呼び出す必要があります。ConfigureEndpointDefaults
and ConfigureHttpsDefaults
should be called before any endpoints are configured.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureEndpointDefaults(listenOptions =>
{
// Configure endpoint defaults
});
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
listenOptions.SslProtocols = SslProtocols.Tls12;
});
});
Kestrel による SNI のサポートKestrel support for SNI
Server Name Indication (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. コールバックは接続ごとに 1 回呼び出されるので、アプリはそれを使って、ホスト名を検査し、適切な証明書を選択できます。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:
- ターゲット フレームワーク
netcoreapp2.1
以降で実行される必要があります。Running on target frameworknetcoreapp2.1
or later.net461
以降、コールバックは呼び出されますが、name
は常にnull
です。Onnet461
or later, the callback is invoked but thename
is alwaysnull
. クライアントが TLS ハンドシェイクでホスト名パラメーターを提供しない場合も、name
はnull
です。Thename
is alsonull
if the client doesn't provide the host name parameter in the TLS handshake. - すべての Web サイトは、同じ Kestrel インスタンスで実行されます。All websites run on the same Kestrel instance. Kestrel では、リバース プロキシは使用しない、複数のインスタンスでの IP アドレスとポートの共有はサポートしていません。Kestrel doesn't support sharing an IP address and port across multiple instances without a reverse proxy.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.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;
};
});
});
});
接続のログ記録Connection logging
接続でのバイト レベルの通信に対してデバッグ レベルのログを出力するには、UseConnectionLogging を呼び出します。Call UseConnectionLogging to emit Debug level logs for byte-level communication on a connection. 接続のログ記録は、TLS 暗号化の間やプロキシの内側など、低レベルの通信での問題のトラブルシューティングに役立ちます。Connection logging is helpful for troubleshooting problems in low-level communication, such as during TLS encryption and behind proxies. UseConnectionLogging
が UseHttps
の前に配置されている場合は、暗号化されたトラフィックがログに記録されます。If UseConnectionLogging
is placed before UseHttps
, encrypted traffic is logged. UseConnectionLogging
が UseHttps
の後に配置されている場合は、暗号化解除されたトラフィックがログに記録されます。If UseConnectionLogging
is placed after UseHttps
, decrypted traffic is logged.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
{
listenOptions.UseConnectionLogging();
});
});
TCP ソケットにバインドするBind to a TCP socket
Listen メソッドは TCP ソケットにバインドし、オプションのラムダにより 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)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001,
listenOptions =>
{
listenOptions.UseHttps("testCert.pfx",
"testPassword");
});
})
.UseStartup<Startup>();
});
例では、ListenOptions を使用して、エンドポイントに対する HTTPS が構成されます。The example configures HTTPS for an endpoint with ListenOptions. 同じ API を使用して、特定のエンドポイントに対する他の Kestrel 設定を構成します。Use the same API to configure other Kestrel settings for specific endpoints.
Windows の場合は、New-SelfSignedCertificate PowerShell コマンドレットを使用して自己署名証明書を作成できます。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
次の例に示すように、Nginx でのパフォーマンスの向上のために ListenUnixSocket を使って UNIX ソケットをリッスンします。Listen on a Unix socket with ListenUnixSocket for improved performance with Nginx, as shown in this example:
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ListenUnixSocket("/tmp/kestrel-test.sock");
serverOptions.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 argumenturls
ホスト構成キーurls
host configuration keyASPNETCORE_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 エンドポイントの構成で (たとえば、前に説明したように
KestrelServerOptions
構成または構成ファイルを使用して) 既定の証明書が提供されていない場合、これらの方法で HTTPS を使用することはできません。HTTPS can't be used with these approaches unless a default certificate is provided in the HTTPS endpoint configuration (for example, usingKestrelServerOptions
configuration or a configuration file as shown earlier in this topic). Listen
とUseUrls
両方の方法を同時に使用すると、Listen
エンドポイントがUseUrls
エンドポイントをオーバーライドします。When both theListen
andUseUrls
approaches are used simultaneously, theListen
endpoints override theUseUrls
endpoints.
IIS エンドポイントの構成IIS endpoint configuration
IIS を使用するときは、IIS オーバーライド バインドに対する URL バインドを、Listen
または UseUrls
によって設定します。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 なしで使用できます。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. HTTP/2 では、クライアントが TLS アプリケーション レイヤー プロトコル ネゴシエーション (ALPN) ハンドシェイクで HTTP/2 を選択する必要があります。それ以外の場合、接続は既定で HTTP/1.1 となります。HTTP/2 requires the client to select HTTP/2 in the TLS Application-Layer Protocol Negotiation (ALPN) handshake; otherwise, the connection defaults to HTTP/1.1. |
任意のエンドポイントに対する ListenOptions.Protocols
の既定値は HttpProtocols.Http1AndHttp2
です。The default ListenOptions.Protocols
value for any endpoint is HttpProtocols.Http1AndHttp2
.
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:
- 暗号スイートはブラック リストに登録されないCipher suite not blacklisted
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
[TLS-ECDHE
] と P-256 elliptic curve [FIPS186
] の組み合わせは既定ではサポートされています。TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
[TLS-ECDHE
] with the P-256 elliptic curve [FIPS186
] is supported by default.
次の例では、HTTP/1.1 接続と HTTP/2 接続がポート 8000 上で許可されています。The following example permits HTTP/1.1 and HTTP/2 connections on port 8000. 接続は、TLS と指定した証明書によってセキュリティで保護されます。Connections are secured by TLS with a supplied certificate:
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
});
必要に応じて、接続ミドルウェアを使用し、特定の暗号のために接続ごとに TLS ハンドシェイクをフィルター処理します。Use Connection Middleware to filter TLS handshakes on a per-connection basis for specific ciphers if required.
次の例では、アプリでサポートされていないすべての暗号アルゴリズムに対して NotSupportedException がスローされます。The following example throws NotSupportedException for any cipher algorithm that the app doesn't support. または、ITlsHandshakeFeature.CipherAlgorithm を定義して、指定できる暗号スイートの一覧と比較します。Alternatively, define and compare ITlsHandshakeFeature.CipherAlgorithm to a list of acceptable cipher suites.
CipherAlgorithmType.Null 暗号アルゴリズムでは、暗号化は使用されません。No encryption is used with a CipherAlgorithmType.Null cipher algorithm.
// using System.Net;
// using Microsoft.AspNetCore.Connections;
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
listenOptions.UseTlsFilter();
});
});
using System;
using System.Security.Authentication;
using Microsoft.AspNetCore.Connections.Features;
namespace Microsoft.AspNetCore.Connections
{
public static class TlsFilterConnectionMiddlewareExtensions
{
public static IConnectionBuilder UseTlsFilter(
this IConnectionBuilder builder)
{
return builder.Use((connection, next) =>
{
var tlsFeature = connection.Features.Get<ITlsHandshakeFeature>();
if (tlsFeature.CipherAlgorithm == CipherAlgorithmType.Null)
{
throw new NotSupportedException("Prohibited cipher: " +
tlsFeature.CipherAlgorithm);
}
return next();
});
}
}
}
接続のフィルター処理は、IConnectionBuilder のラムダを使って構成することもできます。Connection filtering can also be configured via an IConnectionBuilder lambda:
// using System;
// using System.Net;
// using System.Security.Authentication;
// using Microsoft.AspNetCore.Connections;
// using Microsoft.AspNetCore.Connections.Features;
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
listenOptions.Use((context, next) =>
{
var tlsFeature = context.Features.Get<ITlsHandshakeFeature>();
if (tlsFeature.CipherAlgorithm == CipherAlgorithmType.Null)
{
throw new NotSupportedException(
$"Prohibited cipher: {tlsFeature.CipherAlgorithm}");
}
return next();
});
});
});
Linux では、CipherSuitesPolicy を使って、接続ごとに TLS ハンドシェイクをフィルター処理できます。On Linux, CipherSuitesPolicy can be used to filter TLS handshakes on a per-connection basis:
// using System.Net.Security;
// using Microsoft.AspNetCore.Hosting;
// using Microsoft.AspNetCore.Server.Kestrel.Core;
// using Microsoft.Extensions.DependencyInjection;
// using Microsoft.Extensions.Hosting;
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
listenOptions.OnAuthenticate = (context, sslOptions) =>
{
sslOptions.CipherSuitesPolicy = new CipherSuitesPolicy(
new[]
{
TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
// ...
});
};
});
});
構成からのプロトコルを設定する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 の例では、すべてのエンドポイントにおける既定の接続プロトコルとして HTTP/1.1 を確立しています。The following appsettings.json example establishes HTTP/1.1 as the default connection protocol for all endpoints:
{
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1"
}
}
}
次の appsettings.json の例では、特定のエンドポイントにおける HTTP/1.1 接続プロトコルを確立しています。The following appsettings.json example establishes the HTTP/1.1 connection protocol for a specific endpoint:
{
"Kestrel": {
"Endpoints": {
"HttpsDefaultCert": {
"Url": "https://localhost:5001",
"Protocols": "Http1"
}
}
}
}
構成で設定された値は、コード内で指定されたプロトコルによってオーバーライドされます。Protocols specified in code override values set by configuration.
トランスポート構成Transport configuration
Libuv (UseLibuv) を使用する必要のあるプロジェクトの場合For projects that require the use of Libuv (UseLibuv):
アプリのプロジェクト ファイルに 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="{VERSION}" />
IWebHostBuilder
で UseLibuv を呼び出すCall UseLibuv on theIWebHostBuilder
:public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseLibuv(); webBuilder.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/
IPv6 の
[::]
は IPv4 の0.0.0.0
に相当します。[::]
is the IPv6 equivalent of IPv40.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 orlocalhost
binds to all IPv4 and IPv6 IPs. 異なるホスト名を同じポート上の異なる ASP.NET Core アプリにバインドするには、HTTP.sys を使用するか、または 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.警告
リバース プロキシ構成でのホストにはホストのフィルター処理が必要です。Hosting in a reverse proxy configuration requires host filtering.
localhost
名とポート番号、またはループバック IP とポート番号Hostlocalhost
name with port number or loopback IP with port numberhttp://localhost:5000/ http://127.0.0.1:5000/ http://[::1]:5000/
localhost
が指定された場合、Kestrel は IPv4 ループバック インターフェイスと IPv6 ループバック インターフェイスの両方へのバインドを試みます。Whenlocalhost
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.
これを解決するには、Host Filtering Middleware を使用します。As a workaround, use Host Filtering Middleware. Host Filtering Middleware は、ASP.NET Core アプリに暗黙的に含まれる、Microsoft.AspNetCore.HostFiltering パッケージによって提供されています。Host Filtering Middleware is provided by the Microsoft.AspNetCore.HostFiltering package, which is implicitly provided for ASP.NET Core apps. ミドルウェアは CreateDefaultBuilder によって追加され、そこでは AddHostFiltering が呼び出されます。The 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 は既定では無効です。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.json:appsettings.json:
{
"AllowedHosts": "example.com;localhost"
}
注意
Forwarded Headers Middleware にも AllowedHosts オプションがあります。Forwarded Headers Middleware also has an AllowedHosts option. Forwarded Headers Middleware および Host Filtering Middleware には、異なるシナリオ用に類似した機能があります。Forwarded Headers Middleware and Host Filtering Middleware have similar functionality for different scenarios. リバース プロキシ サーバーまたはロード バランサーを使用して要求を転送するとき、Host
ヘッダーが保存されていない場合、Forwarded Headers Middleware に AllowedHosts
を設定するのが適切です。Setting 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 が一般向けエッジ サーバーとして使用されていたり、Host
ヘッダーが直接転送されたりしている場合、Host Filtering Middleware に AllowedHosts
を設定するのが適切です。Setting 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.
Forwarded Headers Middleware の詳細については、プロキシ サーバーとロード バランサーを使用するために ASP.NET Core を構成する を参照してください。For more information on Forwarded Headers Middleware, see プロキシ サーバーとロード バランサーを使用するために ASP.NET Core を構成する.
Kestrel は、ASP.NET Core 向けのクロスプラットフォーム Web サーバーです。Kestrel is a cross-platform web server for ASP.NET Core. Kestrel は、ASP.NET Core のプロジェクト テンプレートに既定で含まれる Web サーバーです。Kestrel is the web server that's included by default in ASP.NET Core project templates.
Kestrel では、次のシナリオがサポートされます。Kestrel supports the following scenarios:
- HTTPSHTTPS
- Websocket を有効にするために使用される非透過的なアップグレードOpaque upgrade used to enable WebSockets
- Nginx の背後にある高パフォーマンスの UNIX ソケットUnix sockets for high performance behind Nginx
- HTTP/2 (macOS の場合を除く†)HTTP/2 (except on macOS†)
†将来のリリースでは HTTP/2 が macOS 上でサポートされるようになります。†HTTP/2 will be supported on macOS in a future release.
kestrel は、.NET Core がサポートするすべてのプラットフォームおよびバージョンでサポートされます。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
Http/2 は、次の基本要件が満たされている場合に、ASP.NET Core アプリで使用できます。HTTP/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‡
- OpenSSL 1.0.2 以降を使用した Linux (Ubuntu 16.04 以降など)Linux with OpenSSL 1.0.2 or later (for example, Ubuntu 16.04 or later)
- ターゲット フレームワーク: .NET Core 2.2 以降Target framework: .NET Core 2.2 or later
- アプリケーション レイヤー プロトコル ネゴシエーション (ALPN) 接続Application-Layer Protocol Negotiation (ALPN) connection
- TLS 1.2 以降の接続TLS 1.2 or later connection
†将来のリリースでは HTTP/2 が macOS 上でサポートされるようになります。†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. TLS 接続をセキュリティで保護するためには、楕円曲線デジタル署名アルゴリズム (ECDSA) を使用して生成した証明書が必要になる場合があります。A certificate generated using an Elliptic Curve Digital Signature Algorithm (ECDSA) may be required to secure TLS connections.
Http/2 接続が確立されると、HttpRequest.Protocol が HTTP/2
を報告します。If an HTTP/2 connection is established, HttpRequest.Protocol reports HTTP/2
.
Http/2 は既定では無効になっています。HTTP/2 is disabled by default. 構成の詳細については、「Kestrel オプション」セクションと「ListenOptions.Protocols」セクションを参照してください。For more information on configuration, see the Kestrel options and ListenOptions.Protocols sections.
Kestrel とリバース プロキシを使用するタイミングWhen to use Kestrel with a reverse proxy
Kestrel を単独で使用することも、インターネット インフォメーション サービス (IIS)、Nginx、Apache などのリバース プロキシ サーバーと併用することもできます。Kestrel can be used by itself or with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. リバース プロキシ サーバーはネットワークから HTTP 要求を受け取り、これを Kestrel に転送します。A reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.
エッジ (インターネットに接続する) Web サーバーとして使用される Kestrel:Kestrel used as an edge (Internet-facing) web server:
リバース プロキシ構成で使用される Kestrel:Kestrel used in a reverse proxy configuration:
いずれの構成でも、リバース プロキシ サーバーの有無に関わらず、ホスティング構成がサポートされています。Either configuration, with or without a reverse proxy server, is a supported hosting configuration.
リバース プロキシ サーバーのないエッジ サーバーとして使用される Kestrel は、複数のプロセス間で同じ 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. ポートを共有できるリバース プロキシは、一意の IP とポート上の Kestrel に要求を転送することができます。A reverse proxy that can share ports has the ability to forward requests to Kestrel on a unique IP and port.
リバース プロキシ サーバーが必要ない場合であっても、リバース プロキシ サーバーを使用すると次のような利点があります。Even if a reverse proxy server isn't required, using a reverse proxy server might be a good choice.
リバース プロキシ: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. リバース プロキシ サーバーのみで X.509 証明書が必要です。このサーバーでは、プレーンな HTTP を使用して内部ネットワーク上のアプリのサーバーと通信することができます。Only the reverse proxy server requires an X.509 certificate, and that server can communicate with the app's servers on the internal network using plain HTTP.
警告
リバース プロキシ構成でのホストにはホストのフィルター処理が必要です。Hosting in a reverse proxy configuration requires host filtering.
ASP.NET Core アプリで Kestrel を使用する方法How to use Kestrel in ASP.NET Core apps
Microsoft.AspNetCore.Server.Kestrel パッケージは、Microsoft.AspNetCore.App メタパッケージに含まれています。The Microsoft.AspNetCore.Server.Kestrel package is included in the Microsoft.AspNetCore.App metapackage.
ASP.NET Core プロジェクト テンプレートは既定では Kestrel を使用します。ASP.NET Core project templates use Kestrel by default. Program.cs 内のテンプレート コードは CreateDefaultBuilder を呼び出し、これによってバックグラウンドで UseKestrel が呼び出されます。In 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
とホストのビルドについて詳しくは、ASP.NET Core の Web ホスト の "ホストを設定する" セクションをご覧ください。For more information on CreateDefaultBuilder
and building the host, see the Set up a host section of ASP.NET Core の Web ホスト.
CreateDefaultBuilder
を呼び出した後に追加の構成を指定するには、ConfigureKestrel
を使用します。To provide additional configuration after calling CreateDefaultBuilder
, use ConfigureKestrel
:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, serverOptions) =>
{
// Set properties and call methods on serverOptions
});
アプリでホストを設定するための CreateDefaultBuilder
を呼び出さない場合は、ConfigureKestrel
を呼び出す前に UseKestrel を呼び出します。If 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, serverOptions) =>
{
// Set properties and call methods on serverOptions
})
.Build();
host.Run();
}
Kestrel オプションKestrel options
Kestrel Web サーバーには、インターネットに接続する展開で特に有効な制約構成オプションがいくつかあります。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;
次の例の C# コード内で構成されている Kestrel オプションは、構成プロバイダーを使って設定することもできます。Kestrel options, which are configured in C# code in the following examples, can also be set using a configuration provider. たとえば、ファイル構成プロバイダーによって、appsettings.json または "appsettings.{環境}.json" ファイルから Kestrel 構成を読み込むことができます。For example, the File Configuration Provider can load Kestrel configuration from an appsettings.json or appsettings.{Environment}.json file:
{
"Kestrel": {
"Limits": {
"MaxConcurrentConnections": 100,
"MaxConcurrentUpgradedConnections": 100
}
}
}
次の方法のいずれかを使用します。Use one of the following approaches:
Startup.ConfigureServices
で Kestrel を構成する。Configure Kestrel inStartup.ConfigureServices
:IConfiguration
のインスタンスをStartup
クラスに挿入します。Inject an instance ofIConfiguration
into theStartup
class. 以下の例では、挿入された構成がConfiguration
プロパティに割り当てられることを前提としています。The following example assumes that the injected configuration is assigned to theConfiguration
property.Startup.ConfigureServices
で、構成のKestrel
セクションを Kestrel の構成に読み込みます。InStartup.ConfigureServices
, load theKestrel
section of configuration into Kestrel's configuration.// using Microsoft.Extensions.Configuration public void ConfigureServices(IServiceCollection services) { services.Configure<KestrelServerOptions>( Configuration.GetSection("Kestrel")); }
ホストのビルド時に Kestrel を構成する。Configure Kestrel when building the host:
Program.cs で、構成の
Kestrel
セクションを Kestrel の構成に読み込みます。In Program.cs, load theKestrel
section of configuration into Kestrel's configuration:// using Microsoft.Extensions.DependencyInjection; public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure<KestrelServerOptions>( context.Configuration.GetSection("Kestrel")); }) .UseStartup<Startup>();
上記の方法はいずれも、任意の構成プロバイダーで使用できます。Both of the preceding approaches work with any configuration provider.
Keep-Alive タイムアウトKeep-alive timeout
Keep-Alive タイムアウトを取得するか、設定します。Gets or sets the keep-alive timeout. 既定値は 2 分です。Defaults to 2 minutes.
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
クライアントの最大接続数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, serverOptions) =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
HTTP または HTTPS から別のプロトコルにアップグレードされた接続については別個の制限があります (WebSockets 要求に関する制限など)。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, serverOptions) =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
接続の最大数は既定では無制限 (null) です。The maximum number of connections is unlimited (null) by default.
要求本文の最大サイズMaximum request body size
既定の要求本文の最大サイズは、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, serverOptions) =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
ミドルウェア内の特定の要求で設定をオーバーライドします。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 the app configures the limit on a request after the app has started to read the request. MaxRequestBodySize
プロパティが読み取り専用状態にある (制限を構成するには遅すぎる) かどうかを示す IsReadOnly
プロパティがあります。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 Module の背後でアプリがアウト プロセスで実行されるとき、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. 要求制限と応答制限を設定するコードは、プロパティ名およびインターフェイス名に RequestBody
または Response
が使用されることを除けば同じです。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, serverOptions) =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
ミドルウェアでは要求ごとに最小レート制限をオーバーライドします。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 要求の HttpContext.Features
には存在しません。これはプロトコルで要求の多重化に対応するために、要求ごとのレート制限の変更が HTTP/2 でサポートされていないからです。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
サーバーで要求ヘッダーの受信にかかる時間の最大値を取得または設定します。Gets or sets the maximum amount of time the server spends receiving request headers. 既定値は 30 秒です。Defaults to 30 seconds.
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
接続ごとの最大ストリームMaximum streams per connection
HTTP/2 接続ごとの同時要求ストリームの数は、Http2.MaxStreamsPerConnection
によって制限されます。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, serverOptions) =>
{
serverOptions.Limits.Http2.MaxStreamsPerConnection = 100;
});
既定値は 100 です。The default value is 100.
ヘッダー テーブルのサイズHeader table size
HTTP/2 接続では、HTTP ヘッダーは HPACK デコーダーによって圧縮解除されます。The HPACK decoder decompresses HTTP headers for HTTP/2 connections. HPACK デコーダーが使用するヘッダー圧縮テーブルのサイズは Http2.HeaderTableSize
によって制限されます。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, serverOptions) =>
{
serverOptions.Limits.Http2.HeaderTableSize = 4096;
});
既定値は 4096 です。The default value is 4096.
最大フレーム サイズMaximum frame size
受信する HTTP/2 接続フレーム ペイロードの最大サイズは、Http2.MaxFrameSize
によって示されます。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, serverOptions) =>
{
serverOptions.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, serverOptions) =>
{
serverOptions.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, serverOptions) =>
{
serverOptions.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, serverOptions) =>
{
serverOptions.Limits.Http2.InitialStreamWindowSize = 98304;
});
既定値は 96 KB (98,304) です。The default value is 96 KB (98,304).
同期 IOSynchronous IO
AllowSynchronousIO を使うと、要求と応答に対して同期 IO を許可するかどうかを制御できます。AllowSynchronousIO controls whether synchronous IO is allowed for the request and response. 既定値は true
です。The default value is true
.
警告
ブロッキング同期 IO 操作の回数が多いと、スレッド プールの不足を招き、アプリが応答しなくなる可能性があります。A large number of blocking synchronous IO operations can lead to thread pool starvation, which makes the app unresponsive. 非同期 IO をサポートしていないライブラリを使用する場合にのみ AllowSynchronousIO
を有効にしてください。Only enable AllowSynchronousIO
when using a library that doesn't support asynchronous IO.
同期 IO を有効にする例を次に示します。The following example enables synchronous IO:
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.AllowSynchronousIO = true;
});
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.
これらの方法を使うと、1 つまたは複数の 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:
- .NET Core SDK がインストールされるとき。When the .NET Core SDK is installed.
- 証明書を作成するには dev-certs ツールを使います。The dev-certs tool is used to create a certificate.
一部のブラウザーでは、ローカル開発証明書を信頼するには、明示的にアクセス許可を付与する必要があります。Some browsers require granting explicit permission to trust the local development certificate.
プロジェクト テンプレートでは、アプリを HTTPS で実行するように既定で構成され、HTTPS のリダイレクトと HSTS のサポートが含まれます。Project templates configure apps to run on HTTPS by default and include HTTPS redirection and HSTS support.
KestrelServerOptions で Listen または ListenUnixSocket メソッドを呼び出して、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).
KestrelServerOptions
構成:KestrelServerOptions
configuration:
ConfigureEndpointDefaults(Action<ListenOptions>)ConfigureEndpointDefaults(Action<ListenOptions>)
指定した各エンドポイントに対して実行するように、構成の Action
を指定します。Specifies a configuration Action
to run for each specified endpoint. ConfigureEndpointDefaults
を複数回呼び出すと、前の Action
が最後に指定した Action
で置き換えられます。Calling ConfigureEndpointDefaults
multiple times replaces prior Action
s with the last Action
specified.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.ConfigureEndpointDefaults(listenOptions =>
{
// Configure endpoint defaults
});
});
注意
ConfigureEndpointDefaults を呼び出す前に Listen を呼び出すことで作成されるエンドポイントには既定値が適用されません。Endpoints created by calling Listen before calling ConfigureEndpointDefaults won't have the defaults applied.
ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)
各 HTTPS エンドポイントに対して実行するように、構成の Action
を指定します。Specifies a configuration Action
to run for each HTTPS endpoint. ConfigureHttpsDefaults
を複数回呼び出すと、前の Action
が最後に指定した Action
で置き換えられます。Calling ConfigureHttpsDefaults
multiple times replaces prior Action
s with the last Action
specified.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
// certificate is an X509Certificate2
listenOptions.ServerCertificate = certificate;
});
});
注意
ConfigureHttpsDefaults を呼び出す前に Listen を呼び出すことで作成されるエンドポイントには既定値が適用されません。Endpoints created by calling Listen before calling ConfigureHttpsDefaults won't have the defaults applied.
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
HTTPS を使用するように Kestrel を構成します。Configure Kestrel to use HTTPS.
ListenOptions.UseHttps
拡張機能:ListenOptions.UseHttps
extensions:
UseHttps
– 既定の証明書で HTTPS を使うように Kestrel を構成します。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
は、HttpsConnectionAdapterOptions
を構成するためのAction
です。configureOptions
is anAction
to configure theHttpsConnectionAdapterOptions
.ListenOptions
を返します。Returns theListenOptions
.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:5000
と https://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
は既定で Configure(context.Configuration.GetSection("Kestrel"))
を呼び出して Kestrel の構成を読み込みます。CreateDefaultBuilder
calls 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 totrue
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>"
}
}
}
}
証明書ノードの Path と 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. たとえば、
HTTPS
とHttps
は有効です。For example,HTTPS
andHttps
are valid. Url
パラメーターは、エンドポイントごとに必要です。TheUrl
parameter is required for each endpoint. このパラメーターの形式は、1 つの値に制限されることを除き、最上位レベルのUrls
構成パラメーターと同じです。The format for this parameter is the same as the top-levelUrls
configuration parameter except that it's limited to a single value.- これらのエンドポイントは、最上位レベルの
Urls
構成での定義に追加されるのではなく、それを置き換えます。These endpoints replace those defined in the top-levelUrls
configuration rather than adding to them. コードでListen
を使用して定義されているエンドポイントは、構成セクションで定義されているエンドポイントに累積されます。Endpoints defined in code viaListen
are cumulative with the endpoints defined in the configuration section. Certificate
セクションは省略可能です。TheCertificate
section is optional.Certificate
セクションを指定しないと、前述のシナリオで定義した既定値が使用されます。If theCertificate
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
セクションは、Path–Password 証明書と Subject–Store 証明書の両方をサポートします。TheCertificate
section supports both Path–Password and Subject–Store 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("{SECTION}"))
が.Endpoint(string name, listenOptions => { })
メソッドで返すKestrelConfigurationLoader
を使用して、構成されているエンドポイントの設定を補足できます。options.Configure(context.Configuration.GetSection("{SECTION}"))
returns aKestrelConfigurationLoader
with an.Endpoint(string name, listenOptions => { })
method that can be used to supplement a configured endpoint's settings:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel((context, serverOptions) =>
{
serverOptions.Configure(context.Configuration.GetSection("Kestrel"))
.Endpoint("HTTPS", listenOptions =>
{
listenOptions.HttpsOptions.SslProtocols = SslProtocols.Tls12;
});
});
KestrelServerOptions.ConfigurationLoader
に直接アクセスして、既存のローダー (CreateDefaultBuilder によって提供されるものなど) の反復を維持することができます。KestrelServerOptions.ConfigurationLoader
can be directly accessed to continue iterating on the existing loader, such as the one provided by CreateDefaultBuilder.
- カスタム設定を読み取ることができるように、各エンドポイントの構成セクションを
Endpoint
メソッドのオプションで使用できます。The configuration section for each endpoint is available on the options in theEndpoint
method so that custom settings may be read. - 別のセクションで
options.Configure(context.Configuration.GetSection("{SECTION}"))
を再び呼び出すことにより、複数の構成を読み込むことができます。Multiple configurations may be loaded by callingoptions.Configure(context.Configuration.GetSection("{SECTION}"))
again with another section. 前のインスタンスでLoad
を明示的に呼び出していない限り、最後の構成のみが使用されます。Only the last configuration is used, unlessLoad
is explicitly called on prior instances. 既定の構成セクションを置き換えることができるように、メタパッケージはLoad
を呼び出しません。The metapackage doesn't callLoad
so that its default configuration section may be replaced. KestrelConfigurationLoader
はミラー、KestrelServerOptions
から API のListen
ファミリをEndpoint
オーバーロードとしてミラーリングするので、コードと構成のエンドポイントを同じ場所で構成できます。KestrelConfigurationLoader
mirrors theListen
family of APIs fromKestrelServerOptions
asEndpoint
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
ConfigureEndpointDefaults
およびConfigureHttpsDefaults
を使用して、ListenOptions
および HttpsConnectionAdapterOptions
の既定の設定を変更できます (前のシナリオで指定した既定の証明書のオーバーライドなど)。ConfigureEndpointDefaults
and ConfigureHttpsDefaults
can be used to change default settings for ListenOptions
and HttpsConnectionAdapterOptions
, including overriding the default certificate specified in the prior scenario. エンドポイントを構成する前に、ConfigureEndpointDefaults
および ConfigureHttpsDefaults
を呼び出す必要があります。ConfigureEndpointDefaults
and ConfigureHttpsDefaults
should be called before any endpoints are configured.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel((context, serverOptions) =>
{
serverOptions.ConfigureEndpointDefaults(listenOptions =>
{
// Configure endpoint defaults
});
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
listenOptions.SslProtocols = SslProtocols.Tls12;
});
});
Kestrel による SNI のサポートKestrel support for SNI
Server Name Indication (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. コールバックは接続ごとに 1 回呼び出されるので、アプリはそれを使って、ホスト名を検査し、適切な証明書を選択できます。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:
- ターゲット フレームワーク
netcoreapp2.1
以降で実行される必要があります。Running on target frameworknetcoreapp2.1
or later.net461
以降、コールバックは呼び出されますが、name
は常にnull
です。Onnet461
or later, the callback is invoked but thename
is alwaysnull
. クライアントが TLS ハンドシェイクでホスト名パラメーターを提供しない場合も、name
はnull
です。Thename
is alsonull
if the client doesn't provide the host name parameter in the TLS handshake. - すべての Web サイトは、同じ Kestrel インスタンスで実行されます。All websites run on the same Kestrel instance. 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, serverOptions) =>
{
serverOptions.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;
};
});
});
});
接続のログ記録Connection logging
接続でのバイト レベルの通信に対してデバッグ レベルのログを出力するには、UseConnectionLogging を呼び出します。Call UseConnectionLogging to emit Debug level logs for byte-level communication on a connection. 接続のログ記録は、TLS 暗号化の間やプロキシの内側など、低レベルの通信での問題のトラブルシューティングに役立ちます。Connection logging is helpful for troubleshooting problems in low-level communication, such as during TLS encryption and behind proxies. UseConnectionLogging
が UseHttps
の前に配置されている場合は、暗号化されたトラフィックがログに記録されます。If UseConnectionLogging
is placed before UseHttps
, encrypted traffic is logged. UseConnectionLogging
が UseHttps
の後に配置されている場合は、暗号化解除されたトラフィックがログに記録されます。If UseConnectionLogging
is placed after UseHttps
, decrypted traffic is logged.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
{
listenOptions.UseConnectionLogging();
});
});
TCP ソケットにバインドするBind to a TCP socket
Listen メソッドは TCP ソケットにバインドし、オプションのラムダにより 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, serverOptions) =>
{
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
});
例では、ListenOptions を使用して、エンドポイントに対する HTTPS が構成されます。The example configures HTTPS for an endpoint with ListenOptions. 同じ API を使用して、特定のエンドポイントに対する他の Kestrel 設定を構成します。Use the same API to configure other Kestrel settings for specific endpoints.
Windows の場合は、New-SelfSignedCertificate PowerShell コマンドレットを使用して自己署名証明書を作成できます。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
次の例に示すように、Nginx でのパフォーマンスの向上のために ListenUnixSocket を使って UNIX ソケットをリッスンします。Listen on a Unix socket with ListenUnixSocket for improved performance with Nginx, as shown in this example:
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.ListenUnixSocket("/tmp/kestrel-test.sock");
serverOptions.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 argumenturls
ホスト構成キーurls
host configuration keyASPNETCORE_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 エンドポイントの構成で (たとえば、前に説明したように
KestrelServerOptions
構成または構成ファイルを使用して) 既定の証明書が提供されていない場合、これらの方法で HTTPS を使用することはできません。HTTPS can't be used with these approaches unless a default certificate is provided in the HTTPS endpoint configuration (for example, usingKestrelServerOptions
configuration or a configuration file as shown earlier in this topic). Listen
とUseUrls
両方の方法を同時に使用すると、Listen
エンドポイントがUseUrls
エンドポイントをオーバーライドします。When both theListen
andUseUrls
approaches are used simultaneously, theListen
endpoints override theUseUrls
endpoints.
IIS エンドポイントの構成IIS endpoint configuration
IIS を使用するときは、IIS オーバーライド バインドに対する URL バインドを、Listen
または UseUrls
によって設定します。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 なしで使用できます。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. HTTP/2 には、TLS とアプリケーション レイヤー プロトコル ネゴシエーション (ALPN) 接続が必要です。それ以外の場合、接続は既定では HTTP/1.1 となります。HTTP/2 requires a TLS and Application-Layer Protocol Negotiation (ALPN) connection; 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:
- 暗号スイートはブラック リストに登録されないCipher suite not blacklisted
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
[TLS-ECDHE
] と P-256 elliptic curve [FIPS186
] の組み合わせは既定ではサポートされています。TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
[TLS-ECDHE
] with the P-256 elliptic curve [FIPS186
] is supported by default.
次の例では、HTTP/1.1 接続と HTTP/2 接続がポート 8000 上で許可されています。The following example permits HTTP/1.1 and HTTP/2 connections on port 8000. 接続は、TLS と指定した証明書によってセキュリティで保護されます。Connections are secured by TLS with a supplied certificate:
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.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:
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.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 the app doesn't
// wish to support. Alternatively, define and compare
// ITlsHandshakeFeature.CipherAlgorithm to a list of acceptable cipher
// suites.
//
// No encryption is used with a CipherAlgorithmType.Null cipher algorithm.
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. これは、UseLibuv を呼び出す 2.1 にアップグレードする 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.Server.Kestrel (パッケージの直接の参照)Microsoft.AspNetCore.Server.Kestrel (direct package reference)
- Microsoft.AspNetCore.AppMicrosoft.AspNetCore.App
Libuv を使用する必要のあるプロジェクトの場合For projects that 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="{VERSION}" />
UseLibuv を呼び出します。Call 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/
IPv6 の
[::]
は IPv4 の0.0.0.0
に相当します。[::]
is the IPv6 equivalent of IPv40.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 orlocalhost
binds to all IPv4 and IPv6 IPs. 異なるホスト名を同じポート上の異なる ASP.NET Core アプリにバインドするには、HTTP.sys を使用するか、または 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.警告
リバース プロキシ構成でのホストにはホストのフィルター処理が必要です。Hosting in a reverse proxy configuration requires host filtering.
localhost
名とポート番号、またはループバック IP とポート番号Hostlocalhost
name with port number or loopback IP with port numberhttp://localhost:5000/ http://127.0.0.1:5000/ http://[::1]:5000/
localhost
が指定された場合、Kestrel は IPv4 ループバック インターフェイスと IPv6 ループバック インターフェイスの両方へのバインドを試みます。Whenlocalhost
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.
これを解決するには、Host Filtering Middleware を使用します。As a workaround, use Host Filtering Middleware. Host Filtering Middleware は、Microsoft.AspNetCore.App metapackage (ASP.NET Core 2.1 または 2.2) に含まれる、Microsoft.AspNetCore.HostFiltering パッケージによって提供されています。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 2.2). ミドルウェアは CreateDefaultBuilder によって追加され、そこでは AddHostFiltering が呼び出されます。The 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 は既定では無効です。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.json:appsettings.json:
{
"AllowedHosts": "example.com;localhost"
}
注意
Forwarded Headers Middleware にも AllowedHosts オプションがあります。Forwarded Headers Middleware also has an AllowedHosts option. Forwarded Headers Middleware および Host Filtering Middleware には、異なるシナリオ用に類似した機能があります。Forwarded Headers Middleware and Host Filtering Middleware have similar functionality for different scenarios. リバース プロキシ サーバーまたはロード バランサーを使用して要求を転送するとき、Host
ヘッダーが保存されていない場合、Forwarded Headers Middleware に AllowedHosts
を設定するのが適切です。Setting 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 が一般向けエッジ サーバーとして使用されていたり、Host
ヘッダーが直接転送されたりしている場合、Host Filtering Middleware に AllowedHosts
を設定するのが適切です。Setting 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.
Forwarded Headers Middleware の詳細については、プロキシ サーバーとロード バランサーを使用するために ASP.NET Core を構成する を参照してください。For more information on Forwarded Headers Middleware, see プロキシ サーバーとロード バランサーを使用するために ASP.NET Core を構成する.
Kestrel は、ASP.NET Core 向けのクロスプラットフォーム Web サーバーです。Kestrel is a cross-platform web server for ASP.NET Core. Kestrel は、ASP.NET Core のプロジェクト テンプレートに既定で含まれる Web サーバーです。Kestrel is the web server that's included by default in ASP.NET Core project templates.
Kestrel では、次のシナリオがサポートされます。Kestrel supports the following scenarios:
- HTTPSHTTPS
- Websocket を有効にするために使用される非透過的なアップグレードOpaque upgrade used to enable WebSockets
- Nginx の背後にある高パフォーマンスの UNIX ソケットUnix sockets for high performance behind Nginx
kestrel は、.NET Core がサポートするすべてのプラットフォームおよびバージョンでサポートされます。Kestrel is supported on all platforms and versions that .NET Core supports.
サンプル コードを表示またはダウンロードします (ダウンロード方法)。View or download sample code (how to download)
Kestrel とリバース プロキシを使用するタイミングWhen to use Kestrel with a reverse proxy
Kestrel を単独で使用することも、インターネット インフォメーション サービス (IIS)、Nginx、Apache などのリバース プロキシ サーバーと併用することもできます。Kestrel can be used by itself or with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. リバース プロキシ サーバーはネットワークから HTTP 要求を受け取り、これを Kestrel に転送します。A reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.
エッジ (インターネットに接続する) Web サーバーとして使用される Kestrel:Kestrel used as an edge (Internet-facing) web server:
リバース プロキシ構成で使用される Kestrel:Kestrel used in a reverse proxy configuration:
いずれの構成でも、リバース プロキシ サーバーの有無に関わらず、ホスティング構成がサポートされています。Either configuration, with or without a reverse proxy server, is a supported hosting configuration.
リバース プロキシ サーバーのないエッジ サーバーとして使用される Kestrel は、複数のプロセス間で同じ 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. ポートを共有できるリバース プロキシは、一意の IP とポート上の Kestrel に要求を転送することができます。A reverse proxy that can share ports has the ability to forward requests to Kestrel on a unique IP and port.
リバース プロキシ サーバーが必要ない場合であっても、リバース プロキシ サーバーを使用すると次のような利点があります。Even if a reverse proxy server isn't required, using a reverse proxy server might be a good choice.
リバース プロキシ: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. リバース プロキシ サーバーのみで X.509 証明書が必要です。このサーバーでは、プレーンな HTTP を使用して内部ネットワーク上のアプリのサーバーと通信することができます。Only the reverse proxy server requires an X.509 certificate, and that server can communicate with the app's servers on the internal network using plain HTTP.
警告
リバース プロキシ構成でのホストにはホストのフィルター処理が必要です。Hosting in a reverse proxy configuration requires host filtering.
ASP.NET Core アプリで Kestrel を使用する方法How to use Kestrel in ASP.NET Core apps
Microsoft.AspNetCore.Server.Kestrel パッケージは、Microsoft.AspNetCore.App メタパッケージに含まれています。The Microsoft.AspNetCore.Server.Kestrel package is included in the Microsoft.AspNetCore.App metapackage.
ASP.NET Core プロジェクト テンプレートは既定では Kestrel を使用します。ASP.NET Core project templates use Kestrel by default. Program.cs 内のテンプレート コードは CreateDefaultBuilder を呼び出し、これによってバックグラウンドで UseKestrel が呼び出されます。In Program.cs, the template code calls CreateDefaultBuilder, which calls UseKestrel behind the scenes.
CreateDefaultBuilder
を呼び出した後に追加の構成を指定するには、UseKestrel を呼び出します。To provide additional configuration after calling CreateDefaultBuilder
, call UseKestrel:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
// Set properties and call methods on serverOptions
});
CreateDefaultBuilder
とホストのビルドについて詳しくは、ASP.NET Core の Web ホスト の "ホストを設定する" セクションをご覧ください。For more information on CreateDefaultBuilder
and building the host, see the Set up a host section of ASP.NET Core の Web ホスト.
Kestrel オプションKestrel options
Kestrel Web サーバーには、インターネットに接続する展開で特に有効な制約構成オプションがいくつかあります。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;
次の例の C# コード内で構成されている Kestrel オプションは、構成プロバイダーを使って設定することもできます。Kestrel options, which are configured in C# code in the following examples, can also be set using a configuration provider. たとえば、ファイル構成プロバイダーによって、appsettings.json または "appsettings.{環境}.json" ファイルから Kestrel 構成を読み込むことができます。For example, the File Configuration Provider can load Kestrel configuration from an appsettings.json or appsettings.{Environment}.json file:
{
"Kestrel": {
"Limits": {
"MaxConcurrentConnections": 100,
"MaxConcurrentUpgradedConnections": 100
}
}
}
次の方法のいずれかを使用します。Use one of the following approaches:
Startup.ConfigureServices
で Kestrel を構成する。Configure Kestrel inStartup.ConfigureServices
:IConfiguration
のインスタンスをStartup
クラスに挿入します。Inject an instance ofIConfiguration
into theStartup
class. 以下の例では、挿入された構成がConfiguration
プロパティに割り当てられることを前提としています。The following example assumes that the injected configuration is assigned to theConfiguration
property.Startup.ConfigureServices
で、構成のKestrel
セクションを Kestrel の構成に読み込みます。InStartup.ConfigureServices
, load theKestrel
section of configuration into Kestrel's configuration.// using Microsoft.Extensions.Configuration public void ConfigureServices(IServiceCollection services) { services.Configure<KestrelServerOptions>( Configuration.GetSection("Kestrel")); }
ホストのビルド時に Kestrel を構成する。Configure Kestrel when building the host:
Program.cs で、構成の
Kestrel
セクションを Kestrel の構成に読み込みます。In Program.cs, load theKestrel
section of configuration into Kestrel's configuration:// using Microsoft.Extensions.DependencyInjection; public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure<KestrelServerOptions>( context.Configuration.GetSection("Kestrel")); }) .UseStartup<Startup>();
上記の方法はいずれも、任意の構成プロバイダーで使用できます。Both of the preceding approaches work with any configuration provider.
Keep-Alive タイムアウトKeep-alive timeout
Keep-Alive タイムアウトを取得するか、設定します。Gets or sets the keep-alive timeout. 既定値は 2 分です。Defaults to 2 minutes.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.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:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
});
HTTP または HTTPS から別のプロトコルにアップグレードされた接続については別個の制限があります (WebSockets 要求に関する制限など)。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.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
});
接続の最大数は既定では無制限 (null) です。The maximum number of connections is unlimited (null) by default.
要求本文の最大サイズMaximum request body size
既定の要求本文の最大サイズは、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:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
});
ミドルウェア内の特定の要求で設定をオーバーライドします。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 the app configures the limit on a request after the app has started to read the request. MaxRequestBodySize
プロパティが読み取り専用状態にある (制限を構成するには遅すぎる) かどうかを示す IsReadOnly
プロパティがあります。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 Module の背後でアプリがアウト プロセスで実行されるとき、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. 要求制限と応答制限を設定するコードは、プロパティ名およびインターフェイス名に RequestBody
または Response
が使用されることを除けば同じです。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:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
});
要求ヘッダー タイムアウトRequest headers timeout
サーバーで要求ヘッダーの受信にかかる時間の最大値を取得または設定します。Gets or sets the maximum amount of time the server spends receiving request headers. 既定値は 30 秒です。Defaults to 30 seconds.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(1);
});
同期 IOSynchronous IO
AllowSynchronousIO を使うと、要求と応答に対して同期 IO を許可するかどうかを制御できます。AllowSynchronousIO controls whether synchronous IO is allowed for the request and response. 既定値は true
です。The default value is true
.
警告
ブロッキング同期 IO 操作の回数が多いと、スレッド プールの不足を招き、アプリが応答しなくなる可能性があります。A large number of blocking synchronous IO operations can lead to thread pool starvation, which makes the app unresponsive. 非同期 IO をサポートしていないライブラリを使用する場合にのみ AllowSynchronousIO
を有効にしてください。Only enable AllowSynchronousIO
when using a library that doesn't support asynchronous IO.
同期 IO を無効にする例を次に示します。The following example disables synchronous IO:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.AllowSynchronousIO = false;
});
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.
これらの方法を使うと、1 つまたは複数の 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:
- .NET Core SDK がインストールされるとき。When the .NET Core SDK is installed.
- 証明書を作成するには dev-certs ツールを使います。The dev-certs tool is used to create a certificate.
一部のブラウザーでは、ローカル開発証明書を信頼するには、明示的にアクセス許可を付与する必要があります。Some browsers require granting explicit permission to trust the local development certificate.
プロジェクト テンプレートでは、アプリを HTTPS で実行するように既定で構成され、HTTPS のリダイレクトと HSTS のサポートが含まれます。Project templates configure apps to run on HTTPS by default and include HTTPS redirection and HSTS support.
KestrelServerOptions で Listen または ListenUnixSocket メソッドを呼び出して、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).
KestrelServerOptions
構成:KestrelServerOptions
configuration:
ConfigureEndpointDefaults(Action<ListenOptions>)ConfigureEndpointDefaults(Action<ListenOptions>)
指定した各エンドポイントに対して実行するように、構成の Action
を指定します。Specifies a configuration Action
to run for each specified endpoint. ConfigureEndpointDefaults
を複数回呼び出すと、前の Action
が最後に指定した Action
で置き換えられます。Calling ConfigureEndpointDefaults
multiple times replaces prior Action
s with the last Action
specified.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.ConfigureEndpointDefaults(listenOptions =>
{
// Configure endpoint defaults
});
});
注意
ConfigureEndpointDefaults を呼び出す前に Listen を呼び出すことで作成されるエンドポイントには既定値が適用されません。Endpoints created by calling Listen before calling ConfigureEndpointDefaults won't have the defaults applied.
ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)
各 HTTPS エンドポイントに対して実行するように、構成の Action
を指定します。Specifies a configuration Action
to run for each HTTPS endpoint. ConfigureHttpsDefaults
を複数回呼び出すと、前の Action
が最後に指定した Action
で置き換えられます。Calling ConfigureHttpsDefaults
multiple times replaces prior Action
s with the last Action
specified.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
// certificate is an X509Certificate2
listenOptions.ServerCertificate = certificate;
});
});
注意
ConfigureHttpsDefaults を呼び出す前に Listen を呼び出すことで作成されるエンドポイントには既定値が適用されません。Endpoints created by calling Listen before calling ConfigureHttpsDefaults won't have the defaults applied.
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
HTTPS を使用するように Kestrel を構成します。Configure Kestrel to use HTTPS.
ListenOptions.UseHttps
拡張機能:ListenOptions.UseHttps
extensions:
UseHttps
– 既定の証明書で HTTPS を使うように Kestrel を構成します。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
は、HttpsConnectionAdapterOptions
を構成するためのAction
です。configureOptions
is anAction
to configure theHttpsConnectionAdapterOptions
.ListenOptions
を返します。Returns theListenOptions
.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:5000
と https://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
は既定で Configure(context.Configuration.GetSection("Kestrel"))
を呼び出して Kestrel の構成を読み込みます。CreateDefaultBuilder
calls 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 totrue
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>"
}
}
}
}
証明書ノードの Path と 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. たとえば、
HTTPS
とHttps
は有効です。For example,HTTPS
andHttps
are valid. Url
パラメーターは、エンドポイントごとに必要です。TheUrl
parameter is required for each endpoint. このパラメーターの形式は、1 つの値に制限されることを除き、最上位レベルのUrls
構成パラメーターと同じです。The format for this parameter is the same as the top-levelUrls
configuration parameter except that it's limited to a single value.- これらのエンドポイントは、最上位レベルの
Urls
構成での定義に追加されるのではなく、それを置き換えます。These endpoints replace those defined in the top-levelUrls
configuration rather than adding to them. コードでListen
を使用して定義されているエンドポイントは、構成セクションで定義されているエンドポイントに累積されます。Endpoints defined in code viaListen
are cumulative with the endpoints defined in the configuration section. Certificate
セクションは省略可能です。TheCertificate
section is optional.Certificate
セクションを指定しないと、前述のシナリオで定義した既定値が使用されます。If theCertificate
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
セクションは、Path–Password 証明書と Subject–Store 証明書の両方をサポートします。TheCertificate
section supports both Path–Password and Subject–Store 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("{SECTION}"))
が.Endpoint(string name, listenOptions => { })
メソッドで返すKestrelConfigurationLoader
を使用して、構成されているエンドポイントの設定を補足できます。options.Configure(context.Configuration.GetSection("{SECTION}"))
returns aKestrelConfigurationLoader
with an.Endpoint(string name, listenOptions => { })
method that can be used to supplement a configured endpoint's settings:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel((context, serverOptions) =>
{
serverOptions.Configure(context.Configuration.GetSection("Kestrel"))
.Endpoint("HTTPS", listenOptions =>
{
listenOptions.HttpsOptions.SslProtocols = SslProtocols.Tls12;
});
});
KestrelServerOptions.ConfigurationLoader
に直接アクセスして、既存のローダー (CreateDefaultBuilder によって提供されるものなど) の反復を維持することができます。KestrelServerOptions.ConfigurationLoader
can be directly accessed to continue iterating on the existing loader, such as the one provided by CreateDefaultBuilder.
- カスタム設定を読み取ることができるように、各エンドポイントの構成セクションを
Endpoint
メソッドのオプションで使用できます。The configuration section for each endpoint is available on the options in theEndpoint
method so that custom settings may be read. - 別のセクションで
options.Configure(context.Configuration.GetSection("{SECTION}"))
を再び呼び出すことにより、複数の構成を読み込むことができます。Multiple configurations may be loaded by callingoptions.Configure(context.Configuration.GetSection("{SECTION}"))
again with another section. 前のインスタンスでLoad
を明示的に呼び出していない限り、最後の構成のみが使用されます。Only the last configuration is used, unlessLoad
is explicitly called on prior instances. 既定の構成セクションを置き換えることができるように、メタパッケージはLoad
を呼び出しません。The metapackage doesn't callLoad
so that its default configuration section may be replaced. KestrelConfigurationLoader
はミラー、KestrelServerOptions
から API のListen
ファミリをEndpoint
オーバーロードとしてミラーリングするので、コードと構成のエンドポイントを同じ場所で構成できます。KestrelConfigurationLoader
mirrors theListen
family of APIs fromKestrelServerOptions
asEndpoint
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
ConfigureEndpointDefaults
およびConfigureHttpsDefaults
を使用して、ListenOptions
および HttpsConnectionAdapterOptions
の既定の設定を変更できます (前のシナリオで指定した既定の証明書のオーバーライドなど)。ConfigureEndpointDefaults
and ConfigureHttpsDefaults
can be used to change default settings for ListenOptions
and HttpsConnectionAdapterOptions
, including overriding the default certificate specified in the prior scenario. エンドポイントを構成する前に、ConfigureEndpointDefaults
および ConfigureHttpsDefaults
を呼び出す必要があります。ConfigureEndpointDefaults
and ConfigureHttpsDefaults
should be called before any endpoints are configured.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel((context, serverOptions) =>
{
serverOptions.ConfigureEndpointDefaults(listenOptions =>
{
// Configure endpoint defaults
});
serverOptions.ConfigureHttpsDefaults(listenOptions =>
{
listenOptions.SslProtocols = SslProtocols.Tls12;
});
});
Kestrel による SNI のサポートKestrel support for SNI
Server Name Indication (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. コールバックは接続ごとに 1 回呼び出されるので、アプリはそれを使って、ホスト名を検査し、適切な証明書を選択できます。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:
- ターゲット フレームワーク
netcoreapp2.1
以降で実行される必要があります。Running on target frameworknetcoreapp2.1
or later.net461
以降、コールバックは呼び出されますが、name
は常にnull
です。Onnet461
or later, the callback is invoked but thename
is alwaysnull
. クライアントが TLS ハンドシェイクでホスト名パラメーターを提供しない場合も、name
はnull
です。Thename
is alsonull
if the client doesn't provide the host name parameter in the TLS handshake. - すべての Web サイトは、同じ Kestrel インスタンスで実行されます。All websites run on the same Kestrel instance. 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>()
.UseKestrel((context, serverOptions) =>
{
serverOptions.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();
接続のログ記録Connection logging
接続でのバイト レベルの通信に対してデバッグ レベルのログを出力するには、UseConnectionLogging を呼び出します。Call UseConnectionLogging to emit Debug level logs for byte-level communication on a connection. 接続のログ記録は、TLS 暗号化の間やプロキシの内側など、低レベルの通信での問題のトラブルシューティングに役立ちます。Connection logging is helpful for troubleshooting problems in low-level communication, such as during TLS encryption and behind proxies. UseConnectionLogging
が UseHttps
の前に配置されている場合は、暗号化されたトラフィックがログに記録されます。If UseConnectionLogging
is placed before UseHttps
, encrypted traffic is logged. UseConnectionLogging
が UseHttps
の後に配置されている場合は、暗号化解除されたトラフィックがログに記録されます。If UseConnectionLogging
is placed after UseHttps
, decrypted traffic is logged.
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
{
listenOptions.UseConnectionLogging();
});
});
TCP ソケットにバインドするBind to a TCP socket
Listen メソッドは TCP ソケットにバインドし、オプションのラムダにより 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>()
.UseKestrel(serverOptions =>
{
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.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(serverOptions =>
{
serverOptions.Listen(IPAddress.Loopback, 5000);
serverOptions.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
});
例では、ListenOptions を使用して、エンドポイントに対する HTTPS が構成されます。The example configures HTTPS for an endpoint with ListenOptions. 同じ API を使用して、特定のエンドポイントに対する他の Kestrel 設定を構成します。Use the same API to configure other Kestrel settings for specific endpoints.
Windows の場合は、New-SelfSignedCertificate PowerShell コマンドレットを使用して自己署名証明書を作成できます。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
次の例に示すように、Nginx でのパフォーマンスの向上のために ListenUnixSocket を使って UNIX ソケットをリッスンします。Listen on a Unix socket with ListenUnixSocket for improved performance with Nginx, as shown in this example:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(serverOptions =>
{
serverOptions.ListenUnixSocket("/tmp/kestrel-test.sock");
serverOptions.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 argumenturls
ホスト構成キーurls
host configuration keyASPNETCORE_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 エンドポイントの構成で (たとえば、前に説明したように
KestrelServerOptions
構成または構成ファイルを使用して) 既定の証明書が提供されていない場合、これらの方法で HTTPS を使用することはできません。HTTPS can't be used with these approaches unless a default certificate is provided in the HTTPS endpoint configuration (for example, usingKestrelServerOptions
configuration or a configuration file as shown earlier in this topic). Listen
とUseUrls
両方の方法を同時に使用すると、Listen
エンドポイントがUseUrls
エンドポイントをオーバーライドします。When both theListen
andUseUrls
approaches are used simultaneously, theListen
endpoints override theUseUrls
endpoints.
IIS エンドポイントの構成IIS endpoint configuration
IIS を使用するときは、IIS オーバーライド バインドに対する URL バインドを、Listen
または UseUrls
によって設定します。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.
トランスポート構成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. これは、UseLibuv を呼び出す 2.1 にアップグレードする 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.Server.Kestrel (パッケージの直接の参照)Microsoft.AspNetCore.Server.Kestrel (direct package reference)
- Microsoft.AspNetCore.AppMicrosoft.AspNetCore.App
Libuv を使用する必要のあるプロジェクトの場合For projects that 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="{VERSION}" />
UseLibuv を呼び出します。Call 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/
IPv6 の
[::]
は IPv4 の0.0.0.0
に相当します。[::]
is the IPv6 equivalent of IPv40.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 orlocalhost
binds to all IPv4 and IPv6 IPs. 異なるホスト名を同じポート上の異なる ASP.NET Core アプリにバインドするには、HTTP.sys を使用するか、または 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.警告
リバース プロキシ構成でのホストにはホストのフィルター処理が必要です。Hosting in a reverse proxy configuration requires host filtering.
localhost
名とポート番号、またはループバック IP とポート番号Hostlocalhost
name with port number or loopback IP with port numberhttp://localhost:5000/ http://127.0.0.1:5000/ http://[::1]:5000/
localhost
が指定された場合、Kestrel は IPv4 ループバック インターフェイスと IPv6 ループバック インターフェイスの両方へのバインドを試みます。Whenlocalhost
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.
これを解決するには、Host Filtering Middleware を使用します。As a workaround, use Host Filtering Middleware. Host Filtering Middleware は、Microsoft.AspNetCore.App metapackage (ASP.NET Core 2.1 または 2.2) に含まれる、Microsoft.AspNetCore.HostFiltering パッケージによって提供されています。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 2.2). ミドルウェアは CreateDefaultBuilder によって追加され、そこでは AddHostFiltering が呼び出されます。The 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 は既定では無効です。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.json:appsettings.json:
{
"AllowedHosts": "example.com;localhost"
}
注意
Forwarded Headers Middleware にも AllowedHosts オプションがあります。Forwarded Headers Middleware also has an AllowedHosts option. Forwarded Headers Middleware および Host Filtering Middleware には、異なるシナリオ用に類似した機能があります。Forwarded Headers Middleware and Host Filtering Middleware have similar functionality for different scenarios. リバース プロキシ サーバーまたはロード バランサーを使用して要求を転送するとき、Host
ヘッダーが保存されていない場合、Forwarded Headers Middleware に AllowedHosts
を設定するのが適切です。Setting 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 が一般向けエッジ サーバーとして使用されていたり、Host
ヘッダーが直接転送されたりしている場合、Host Filtering Middleware に AllowedHosts
を設定するのが適切です。Setting 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.
Forwarded Headers Middleware の詳細については、プロキシ サーバーとロード バランサーを使用するために ASP.NET Core を構成する を参照してください。For more information on Forwarded Headers Middleware, see プロキシ サーバーとロード バランサーを使用するために ASP.NET Core を構成する.
その他の技術情報Additional resources
フィードバック
フィードバックを読み込んでいます...