System.Net.Http Namespace

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:

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:

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:

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:

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:

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