HttpClient is the primary API for making outbound HTTP requests in .NET.
HttpClient
is a wrapper API around an HttpMessageHandler
. The most inner HttpMessageHandler
is the one that's responsible for making the HTTP request. There are several implementations on various .NET platforms. This document is focused on server applications and will focus on 2-3 main implementations:
- HttpClientHandler/WebRequestHandler on .NET Framework
- SocketHttpHandler on .NET Core/5
- WinHttpHandler on .NET Framework or .NET Core/5 (runs on both but is Windows-specific)
WebClient is considered a legacy .NET API at this point and has been completely superseded by HttpClient. New code should be written with HttpClient.
❌ BAD This example uses the legacy WebClient to make a synchronous HTTP request.
public string DoSomethingAsync()
{
var client = new WebClient();
return client.DownloadString("http://www.google.com");
}
✅ GOOD This example uses an HttpClient to asynchronously make an HTTP request.
static readonly HttpClient client = new HttpClient();
public async Task<string> DoSomethingAsync()
{
return await client.GetStringAsync("http://www.google.com");
}