MSDN Documentation

HttpClientHandler Class

Namespace: System.Net.Http

Assembly: System.Net.Http.dll

Description

Provides a programming model for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. This class implements the core logic for sending HTTP requests, handling redirects, cookies, and authentication.

Remarks

The HttpClientHandler class is the default handler used by HttpClient. It provides a flexible way to customize the behavior of HTTP requests. You can override its behavior or create your own handler that inherits from HttpMessageHandler.

Key features include:

  • Automatic handling of redirects.
  • Management of cookies.
  • Support for various authentication schemes.
  • Control over proxy settings.
  • Configuration for SSL/TLS protocols.

When constructing an HttpClient instance, you can provide a custom HttpMessageHandler to tailor the request pipeline. For example, to add custom headers or logging.

Constructors

Name Description
HttpClientHandler() Initializes a new instance of the HttpClientHandler class with default settings.

Properties

Name Type Description
AllowAutoRedirect bool Gets or sets a value that indicates whether the HTTP handler follows HTTP redirect responses automatically.
AutomaticDecompressContent bool Gets or sets a value that indicates whether the HTTP handler automatically decompresses the HTTP content if the content encoding is specified.
ClientCertificateGenerator Func<HttpRequestMessage, X509Certificate2> Gets or sets a delegate that is called to generate a client certificate for an X.509 certificate based authentication.
ClientCertificates X509CertificateCollection Gets or sets the collection of client certificates used to authenticate the handler to the server.
CookieContainer CookieContainer Gets or sets the cookie container used by the handler.
Credentials ICredentials Gets or sets the network credentials for the handler.
MaxAutomaticRedirections int Gets or sets the maximum number of automatic redirections.
PreemptiveAuthentication bool Gets or sets a value that indicates whether the handler sends an authentication request to the server before it receives a challenge from the server.
Proxy IWebProxy Gets or sets the proxy used by the handler.
ReceiveDataTimeout TimeSpan Gets or sets the timeout for receiving data.
UseCookies bool Gets or sets a value that indicates whether the handler uses cookies.
UseProxy bool Gets or sets a value that indicates whether the handler uses the proxy.

Methods

Name Description
Dispose() Releases the unmanaged resources and optionally releases the managed resources.
SendAsync(HttpRequestMessage, CancellationToken) Sends an HTTP request to the given URL with an optional HTTP cancellation token.

AllowAutoRedirect Property

Gets or sets a value that indicates whether the HTTP handler follows HTTP redirect responses automatically.

If true, the handler automatically follows redirects. If false, the handler returns the redirect response as is.

AutomaticDecompressContent Property

Gets or sets a value that indicates whether the HTTP handler automatically decompresses the HTTP content if the content encoding is specified (e.g., gzip, deflate).

If true, the handler automatically decompresses content. If false, the content is returned as received.

ClientCertificateGenerator Property

Gets or sets a delegate that is called to generate a client certificate for an X.509 certificate based authentication.

This is useful when the server requires client certificate authentication and the certificate needs to be dynamically generated or selected.

ClientCertificates Property

Gets or sets the collection of client certificates used to authenticate the handler to the server.

These certificates are sent to the server when a secure connection is established and the server requests client authentication.

CookieContainer Property

Gets or sets the cookie container used by the handler to store and send cookies.

The CookieContainer class manages cookies based on their domain, path, and expiration.

Credentials Property

Gets or sets the network credentials for the handler.

These credentials are used for authentication with the server, such as Basic, Digest, or NTLM authentication.

MaxAutomaticRedirections Property

Gets or sets the maximum number of automatic redirections that will be followed by the handler.

This property is only relevant if AllowAutoRedirect is set to true.

PreemptiveAuthentication Property

Gets or sets a value that indicates whether the handler sends an authentication request to the server before it receives a challenge from the server.

This is part of certain authentication schemes to improve efficiency.

Proxy Property

Gets or sets the proxy used by the handler to send requests to the server.

This property is used when requests need to be routed through a proxy server.

ReceiveDataTimeout Property

Gets or sets the time-out interval in milliseconds for the ReceiveAsync operation.

A timeout value of 0 indicates an infinite time-out.

UseCookies Property

Gets or sets a value that indicates whether the handler uses cookies.

If true, cookies are automatically managed using the CookieContainer.

UseProxy Property

Gets or sets a value that indicates whether the handler uses the proxy.

This property is only relevant if the Proxy property is set.

SendAsync Method

Sends an HTTP request to the given URL with an optional HTTP cancellation token.

This is the core method used to dispatch HTTP requests.

Signature

protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

Example

The following example demonstrates how to use HttpClientHandler to configure custom cookie handling.

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

public class Example
{
    public static async Task MakeRequestWithCustomCookies()
    {
        using (var handler = new HttpClientHandler())
        {
            handler.CookieContainer = new CookieContainer();
            handler.CookieContainer.Add(new Uri("http://example.com"), new Cookie("mycookie", "myvalue"));
            handler.UseCookies = true; // Ensure cookies are used

            using (var httpClient = new HttpClient(handler))
            {
                try
                {
                    HttpResponseMessage response = await httpClient.GetAsync("http://example.com/somepage");
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"\nException Caught!");
                    Console.WriteLine($"Message :{e.Message} ");
                }
            }
        }
    }
}