【Azure App Service】验证App Service接受HTTP 2.0请求

问题描述

在App Service中启用了HTTP 2.0后,如何来验证它可以正常接受HTTP 2.0的请求呢?

问题解答

如果直接使用浏览器访问,无法直接判断出来是否使用 HTTP 2.0,所以本文中使用.NET Console代码来测试HTTP 2.0.

第一步:打开Visual Studio 2022,创建一个.NET Console Application

第二步:添加 HttpClient() 代码,并设置 HttpRequestMessage 的 Version 为2.0

Console.WriteLine("Hello, World!");

var client = new HttpClient() { BaseAddress = new Uri("https://lbphptest01.chinacloudsites.cn/") };

Console.WriteLine("Sending HTTP 2.0 Request.");

// HTTP/2 request
using (var request = new HttpRequestMessage(HttpMethod.Get, "/") { Version = new Version(2, 0) })
using (var response = await client.SendAsync(request))
Console.WriteLine(response);

注意:也可以直接指定 HTTPClient 类 DefaultRequestVersion 属性值

var SecondRequest = new HttpClient()
{
    BaseAddress = new Uri("https://lbphptest01.chinacloudsites.cn/"),
    DefaultRequestVersion = new Version(2, 0)
};

// HTTP/2 is default
using (var response = await SecondRequest.GetAsync("/"))
    Console.WriteLine(response);

 

第三步:运行代码,查看结果 HttpResponse Version 为2.0 

 

附录:示例代码

// .NET Console App的代码使用的.NET 8 Framework并且使用顶级语句(top-level statements)
Console.WriteLine("Hello, World!");

var client = new HttpClient() { BaseAddress = new Uri("https://xxx.chinacloudsites.cn/") }; Console.WriteLine("#1: Sending HTTP 2.0 Request By HttpRequestMessage Version"); // HTTP/2 request using (var request = new HttpRequestMessage(HttpMethod.Get, "/") { Version = new Version(2, 0) }) using (var response = await client.SendAsync(request)) Console.WriteLine(response);
Console.WriteLine(
"#2: Sending HTTP 2.0 Request By HttpClient DefaultRequestVersion"); var SecondRequest = new HttpClient() { BaseAddress = new Uri("https://xxx.chinacloudsites.cn/"), DefaultRequestVersion = new Version(2, 0) }; // HTTP/2 is default using (var response = await SecondRequest.GetAsync("/")) Console.WriteLine(response);
Console.Read();

 

 参考资料

Send HTTP 2.0 Request to App Service using C# : https://techcommunity.microsoft.com/t5/apps-on-azure-blog/send-http-2-0-request-to-app-service-using-c/ba-p/4034469

HttpClient Class:https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-8.0

 

posted @ 2024-04-08 20:39  路边两盏灯  阅读(14)  评论(0编辑  收藏  举报