System.Net.Http Namespace
Provides classes for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. This namespace is the core of modern HTTP client development in .NET.
Key Classes
HttpClient
The primary class for sending HTTP requests. It is designed to be instantiated once and reused throughout the life of an application. This is because HttpClient
is thread-safe and intended to be long-lived. Repeatedly creating HttpClient
instances can lead to socket exhaustion.
Key Members:
GetAsync(string requestUri)
: Sends a GET request to the specified URI.PostAsync(string requestUri, HttpContent content)
: Sends a POST request to the specified URI.PutAsync(string requestUri, HttpContent content)
: Sends a PUT request to the specified URI.DeleteAsync(string requestUri)
: Sends a DELETE request to the specified URI.SendAsync(HttpRequestMessage request)
: Sends an arbitrary HTTP request.
Example Usage of HttpClient
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
try
{
HttpResponseMessage response = await client.GetAsync("https://www.microsoft.com");
response.EnsureSuccessStatusCode(); // Throw if not a success code
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody.Substring(0, 200) + "..."); // Display first 200 chars
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
HttpRequestMessage
Represents an HTTP request message, including the request URI, headers, and content. It's used to construct a request before sending it with HttpClient
.
Key Properties:
Method
: The HTTP method (e.g., GET, POST).RequestUri
: The URI to which the request is sent.Content
: The HTTP content associated with the request.Headers
: The collection of HTTP headers for the request.
HttpResponseMessage
Represents an HTTP response message received from an HTTP server. It's returned by HttpClient.SendAsync
and the convenience methods like GetAsync
.
Key Properties:
StatusCode
: The HTTP status code.ReasonPhrase
: The reason phrase for the status code.Content
: The HTTP content associated with the response.Headers
: The collection of HTTP headers for the response.RequestMessage
: The originating HTTP request.
HttpContent
An abstract base class representing the HTTP content of a resource. Concrete implementations like StringContent
, ByteArrayContent
, and StreamContent
are used to send various types of data in requests or receive data in responses.
Common Implementations:
StringContent
: For sending strings (e.g., JSON, XML).FormUrlEncodedContent
: For sending form data.MultipartFormDataContent
: For sending files and form data in multipart format.
HttpMessageHandler
An abstract base class that is the base for handlers that send HTTP requests or handle the response messages. HttpClient
uses a pipeline of HttpMessageHandler
instances to process requests.
Common Implementations:
HttpClientHandler
: The default handler that sends HTTP requests.WebRequestHandler
: A more configurable handler (though generallyHttpClientHandler
is preferred for new development).
Common Scenarios
Scenario | Key Classes/Methods | Description |
---|---|---|
GET Request | HttpClient.GetAsync() |
Retrieve data from a web service. |
POST Request (JSON) | HttpClient.PostAsync() , StringContent |
Send data, often in JSON format, to create or update a resource. |
File Upload | HttpClient.PostAsync() , MultipartFormDataContent |
Upload files to a web server. |
Custom Headers | HttpRequestMessage.Headers.Add() |
Add custom headers like Authorization or API keys. |
Response Handling | HttpResponseMessage.EnsureSuccessStatusCode() , Content.ReadAsAsync<T>() |
Check for success and deserialize response content. |
Best Practices
- Reuse
HttpClient
: InstantiateHttpClient
once and reuse it. - Asynchronous Operations: Use
async/await
for all HTTP operations to avoid blocking threads. - Error Handling: Always check the
HttpResponseMessage.StatusCode
and useEnsureSuccessStatusCode()
or explicit checks for potential errors. - Dispose Resources: Ensure that
HttpClient
and its related objects are properly disposed of when no longer needed, especially if not reusing globally. - Configure Handlers: Use
HttpClientHandler
or customHttpMessageHandler
for advanced configurations like proxies, cookies, or authentication.