asp.netasp.net-web-apihttpclientsendasyncgetasync

Does all methods of HttpClient internally invoke SendAsync method?


Does all methods of HttpClient i.e. GetAsync, PostAsync etc. internally invoke SendAsync method?


Solution

  • Yes, the HttpClient uses an HttpMessageHandler underneath to perform all HTTP requests. The HttpMessageHandler method Task<HttpResponseMessage> SendAsync(HttpRequestMessage, CancellationToken) is what is called by the HttpClient.

    The default implementation of the abstract class HttpMessageHandler is HttpClientHandler.

    You can pass in your own HttpMessageHandler implementation to the HttpClient constructor that takes one. Although it's highly unlikely you'd ever need to, there are applications. For example, if you wanted to log every request your HttpClient makes. You could make a LoggingHttpMessageHandler decorator for a HttpMessageHandler.

    using (var handler = new HttpClientHandler())
    using (var loggingHandler = new LoggingHttpClientHandler(handler, logger))
    using (var client = new HttpClient(loggingHandler))
    {
        // Logs "GET https://www.google.com/"
        var response = await client.GetAsync("https://www.google.com/");
        ...
    }