使用 ASP.NET Core 的 gRPC 服務(下鏈接有中文源地址)本文章用於自己記錄
配置 Kestrel
Kestrel gRPC 終結點:
- 需要 HTTP/2。
- 應通過傳輸層安全性(TLS)來保護。
HTTP/2
- gRPC 要求 HTTP/2。 gRPC for ASP.NET Core 驗證HttpRequest爲HTTP/2。
- 在大多數現代操作系統上,Kestrel支持 HTTP/2 。 默認情況下,Kestrel 終結點配置爲支持 HTTP/1.1 和 HTTP/2 連接。
TLS
用於 gRPC 的 Kestrel 終結點應使用 TLS 進行保護。 在開發中,將在存在 ASP.NET Core 開發證書https://localhost:5001時,自動創建一個使用 TLS 保護的終結點。 不需要配置。 https前綴驗證 Kestrel 終結點是否正在使用 TLS。
在生產環境中,必須顯式配置 TLS。 在下面的appsettings示例中,提供了使用 TLS 保護的 HTTP/2 終結點:
{
"Kestrel": {
"Endpoints": {
"HttpsInlineCertFile": {
"Url": "https://localhost:5001",
"Protocols": "Http2",
"Certificate": {
"Path": "<path to .pfx file>",
"Password": "<certificate password>"
}
}
}
}
}
或者,可以在Program.cs中配置 Kestrel 終結點:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Any, 5001, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
listenOptions.UseHttps("<path to .pfx file>",
"<certificate password>");
});
});
webBuilder.UseStartup<Startup>();
});
協議協商
TLS 用於保護通信的安全性。 當終結點支持多個協議時,TLS應用層協議協商(ALPN)握手用於協商客戶端與服務器之間的連接協議。 此協商確定連接是使用 HTTP/1.1 還是 HTTP/2。
如果在不使用 TLS 的情況下配置了 HTTP/2 終結點,則終結點的 ListenOptions.Protocols 必須設置爲 HttpProtocols.Http2。 具有多個協議(例如)的終結HttpProtocols.Http1AndHttp2點不能使用 TLS,因爲沒有協商。 到不安全終結點的所有連接默認爲 HTTP/1.1,並且 gRPC 調用失敗。
有關通過 Kestrel 啓用 HTTP/2 和 TLS 的詳細信息,請參閱Kestrel 終結點配置。