Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원 [링크 복사], [링크+제목 복사],
조회: 17452
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 5개 있습니다.)
개발 환경 구성: 361. Azure Web App(App Service)의 HTTP/2 프로토콜 지원
; https://www.sysnet.pe.kr/2/0/11493

웹: 40. IIS의 HTTP/2 지원 여부 - h2, h2c
; https://www.sysnet.pe.kr/2/0/12495

.NET Framework: 1014. ASP.NET Core(Kestrel)의 HTTP/2 지원 여부
; https://www.sysnet.pe.kr/2/0/12500

.NET Framework: 1015. .NET 5부터 HTTP/1.1, 2.0 선택을 위한 HttpVersionPolicy 동작 방식
; https://www.sysnet.pe.kr/2/0/12501

.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원
; https://www.sysnet.pe.kr/2/0/12502




.NET Core HttpClient의 HTTP/2 지원

지난 글까지 HTTP/2의 서버 측 지원을 알아봤는데,

IIS의 HTTP/2 지원 여부 - h2, h2c
; https://www.sysnet.pe.kr/2/0/12495

ASP.NET Core(Kestrel)의 HTTP/2 지원 여부
; https://www.sysnet.pe.kr/2/0/12500

그렇다면 클라이언트 측도 마저 다뤄야겠지요. ^^ 쉬운 테스트를 위해 서버는 nghttp2.org로 정했고, HttpClient는 기본적인 구성부터 시작해 .NET Core 3.1 환경으로 테스트를 해보겠습니다.

// .NET Core 3.1

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient _client;

    static Program()
    {
        _client = new HttpClient();
    }

    static async Task Main()
    {
        try
        {
            {
                using var response = await _client.GetAsync("http://nghttp2.org");
                Console.WriteLine(response.Version);
            }

            {
                using var response = await _client.GetAsync("https://nghttp2.org");
                Console.WriteLine(response.Version);
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

/* 출력 결과
1.1
1.1
*/

http와 https 모두 1.1 응답을 받고 있는데요, 왜냐하면 HttpClient의 기본 버전은 1.1이고 TLS 협상 시 h2 식별자를 사용하지 않기 때문입니다. 따라서, 명시적으로 HTTP/2 통신을 하려면 버전을 지정해야 합니다.

static Program()
{
    _client = new HttpClient()
    {
        // curl의 --http2-prior-knowledge 옵션과 유사한 역할
        DefaultRequestVersion = new Version(2, 0),
    };
}

/* 출력 결과
1.1
2.0
*/

그래도 https의 경우에만 2.0으로 통신이 되었고 http의 경우에는 여전히 1.1로 됩니다. 이유는 애당초 HttpClient는 h2c 모드를 지원하지 않기 때문입니다. 다행히 마이크로소프트는 이를 위해 .NET Core 3.0에서 "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport" 전역 설정을 추가했는데요,

static Program()
{
    AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

    SocketsHttpHandler handler = new SocketsHttpHandler();

    _client = new HttpClient(handler)
    {
        DefaultRequestVersion = new Version(2, 0),
    };
}

/* 출력 결과
2.0
2.0
*/

이제야 비로소 http와 https에 대해 모두 HTTP/2 통신을 할 수 있게 됩니다.




그런데, .NET 5부터 이런 정책이 바뀌었습니다. 위의 예제 코드를 실행하면, 다시 "1.1"과 "2.0" 출력을 확인할 수 있는데요, 결국 "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport" 옵션 설정이 아무런 효력을 내지 못하고 있는 것입니다. (달리 말해, 하위 호환성이 깨지므로, HTTP/2 통신을 하는 기존 코드는 .NET 5로 마이그레이션 시 반드시 코드 변경을 해야 합니다.)

이에 대해서는 아래의 문서에서 언급하고 있으며,

HTTP/2 - Version Selection
; https://devblogs.microsoft.com/dotnet/net-5-new-networking-improvements/#version-selection

따라서 .NET 5부터는 VersionPolicy 속성을 통해 이를 제어해야 합니다. 가령, 기존의 .NET Core 3.x 코드를 .NET 5로 마이그레이션한다면 다음과 같이 HttpVersionPolicy.RequestVersionExact 옵션을 설정하면 동일하게 동작할 수 있습니다.

static Program()
{
    SocketsHttpHandler handler = new SocketsHttpHandler();

    _client = new HttpClient(handler)
    {
        // curl의 --http2-prior-knowledge 옵션과 유사한 역할
        DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact,
        DefaultRequestVersion = new Version(2, 0),
    };
}

버전 선택 정책에 대한 좀 더 자세한 동작 방식은 다음의 글에 별도로 정리했으니 참고하시고,

.NET 5부터 HTTP/1.1, 2.0 선택을 위한 HttpVersionPolicy 동작 방식
; https://www.sysnet.pe.kr/2/0/12501

한 가지 유의할 것은, HttpClient의 경우 h2c 협상에 준하는 동작은 없다는 점입니다. 즉, 처음부터 HTTP/2 또는 HTTP/1.1로 통신을 게시하는 방식입니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/21/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...
NoWriterDateCnt.TitleFile(s)
12435정성태12/1/202025192Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 [1]파일 다운로드1
12434정성태11/30/202019018Windows: 180. C# - dynamicport 값의 범위를 알아내는 방법
12433정성태11/29/202017770Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY파일 다운로드1
12432정성태11/29/202019261Windows: 178. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR [1]파일 다운로드1
12431정성태11/27/202016103.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/202018484오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/202018571디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/202016735VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202017600.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/202015986오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/202017607VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202017928VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202018539.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202015995.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202015282.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202015202오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202016095VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202018343오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202016043오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202017119오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202017396.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019500VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018500.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020660.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017426오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017569디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...