.NET 6 中的(de) HTTP/3 支持
根據官方博客的(de)介紹,.NET 6 提供了(le/liǎo)對 HTTP/3 的(de)預覽支持,主要(yào / yāo)包括以(yǐ)下場景:
在(zài) Kestrel、HTTP.Sys 和(hé / huò) IIS 中,用于(yú) ASP.NET 服務器
在(zài) HttpClient 中發送 outbound 請求
面向 gRPC
.NET 開發團隊表示,HTTP/3 的(de) RFC 還沒有最終确定,但他(tā)們還是(shì)将 HTTP/3 引入到(dào)了(le/liǎo) .NET 6 中,方便用戶開始進行試驗,但這(zhè)隻是(shì) .NET 6 的(de)預覽功能——因爲(wéi / wèi)它不(bù)符合 .NET 6 其餘部分的(de)質量标準。因此需要(yào / yāo)與其他(tā)服務器和(hé / huò)客戶端進行更廣泛的(de)測試以(yǐ)确保兼容性,尤其是(shì)在(zài)邊界情況下。
試用 HTTP/3
如需使用 HTTP/3,需安裝 MSQuic 及其 TLS 依賴項。
目前隻支持 Windows 和(hé / huò) Linux,.NET 6 暫不(bù)支持 macOS 上(shàng)的(de) HTTP/3,主要(yào / yāo)是(shì)因爲(wéi / wèi)缺少與 QUIC 兼容的(de) TLS API。.NET 團隊認爲(wéi / wèi),由于(yú) .NET 在(zài) macOS 上(shàng)使用 SecureTransport 來(lái)實現其 TLS 實現,它尚未包含支持 QUIC 握手的(de) TLS API。雖然可以(yǐ)使用 OpenSSL,但他(tā)們認爲(wéi / wèi)最好不(bù)要(yào / yāo)引入未與操作系統的(de)證書管理集成的(de)附加依賴項。
示例
使用 HTTP/3 的(de) gRPC
gRPC 是(shì)一(yī / yì /yí)種使用 protobuf 序列化格式的(de) RPC 機制。gRPC 通常使用 HTTP/2 作爲(wéi / wèi)其傳輸。HTTP/3 使用了(le/liǎo)相同的(de)語義,因此幾乎不(bù)需要(yào / yāo)更改即可使其工作。gRPC over HTTP/3 由 .NET 團隊提出(chū),目前還不(bù)是(shì)一(yī / yì /yí)個(gè)标準。
ASP.NET Server
var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddGrpc(); builder.WebHost.ConfigureKestrel((context, options) =>{ options.Listen(IPAddress.Any, 5001, listenOptions => { listenOptions.Protocols = HttpProtocols.Http3; listenOptions.UseHttps(); }); });var app = builder.Build();// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.MapGrpcService<GreeterService>(); app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); app.Run();
Client
using Grpc.Net.Client;using GrpcService1;using System.Net;var httpClient = new HttpClient(); httpClient.DefaultRequestVersion = HttpVersion.Version30; httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions() { HttpClient = httpClient });var client = new Greeter.GreeterClient(channel);var response = await client.SayHelloAsync(new HelloRequest { Name = "World" }); Console.WriteLine(response.Message);