gpt4 book ai didi

c# - 如何在 dotnet 核心中为 HttpClient 指定 HTTP/2 "prior knowledge"模式?

转载 作者:行者123 更新时间:2023-12-02 02:58:29 25 4
gpt4 key购买 nike

使用 dotnet Core 3.1,以下服务器接受 HTTP/2 请求:

using System;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using System.Threading;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core;

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

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, serverOptions) =>
{
serverOptions.ListenLocalhost(8080, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2; // this line is important
});
});
}

class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(context => ProcessAsync(context));
}

internal async Task<bool> ProcessAsync(HttpContext context)
{
await context.Response.WriteAsync("This is the response: toto");
return true;
}
}
}

例如,如果您尝试以下操作,您会得到响应:curl --silent --http2-prior-knowledge http://localhost:8080

我的问题是关于如何实际执行 curl 正在执行的操作?但在 C# 中。

我试过:

static void ClientCode(object parameter)
{
SocketsHttpHandler handler = new SocketsHttpHandler();
using (var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8080");
request.Version = new Version(2, 0);

var response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
var s = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(s);
}
}
}

但我只是得到一个异常(exception)。

是否可以使用 prior knowledge mode在 C# 和 dotnet Core 中使用 HttpClient?

最佳答案

我在 net5.0 上,只有在显式设置 VersionPolicy 时才能让它工作

var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5001/test");
request.Version = new Version(2, 0);
request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;

关于c# - 如何在 dotnet 核心中为 HttpClient 指定 HTTP/2 "prior knowledge"模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60553740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com