HttpClientHandler 类

定义

.NET Framework 和 .NET Core 2.0 及更低版本中由 HttpClient 使用的默认消息处理程序。The default message handler used by HttpClient in .NET Framework and .NET Core 2.0 and earlier.

public ref class HttpClientHandler : System::Net::Http::HttpMessageHandler
public class HttpClientHandler : System.Net.Http.HttpMessageHandler
type HttpClientHandler = class
    inherit HttpMessageHandler
Public Class HttpClientHandler
Inherits HttpMessageHandler
继承
HttpClientHandler
派生

示例

static async Task Main()
{
   // Create an HttpClientHandler object and set to use default credentials
   HttpClientHandler handler = new HttpClientHandler();
   handler.UseDefaultCredentials = true;

   // Create an HttpClient object
   HttpClient client = new HttpClient(handler);

   // Call asynchronous network methods in a try/catch block to handle exceptions
   try	
   {
      HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");

      response.EnsureSuccessStatusCode();

      string responseBody = await response.Content.ReadAsStringAsync();
      Console.WriteLine(responseBody);
   }  
   catch(HttpRequestException e)
   {
       Console.WriteLine("\nException Caught!");	
       Console.WriteLine("Message :{0} ",e.Message);
   }

   // Need to call dispose on the HttpClient and HttpClientHandler objects 
   // when done using them, so the app doesn't leak resources
   handler.Dispose(true);
   client.Dispose(true);
}

前面的代码示例使用 async Task Main() 入口点。The preceding code example uses an async Task Main() entry point. 该功能需要C# 7.1 或更高版本。That feature requires C# 7.1 or later.

注解

HttpClientHandler 类和派生自的类使开发人员能够配置各种选项,包括从代理到身份验证。The HttpClientHandler class and classes derived from it enable developers to configure a variety of options ranging from proxies to authentication.

.NET Core 中的 HttpClientHandlerHttpClientHandler in .NET Core

从 .NET Core 2.1 开始,System.Net.Http.SocketsHttpHandler 类而不是 HttpClientHandler 提供更高级别的 HTTP 网络 Api 使用的实现。Starting with .NET Core 2.1, the System.Net.Http.SocketsHttpHandler class instead of HttpClientHandler provides the implementation used by higher-level HTTP networking APIs. 可以通过以下任一方式将应用程序配置为使用 HttpClientHandlerYou can configure your application to use HttpClientHandler instead in any of the following ways:

  • 通过调用 AppContext.SetSwitch 方法,如下所示:By calling the AppContext.SetSwitch method as follows:

    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
    
    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", False)
    
  • 通过在netcore. runtimeconfig.template.json配置文件中定义 System.Net.Http.UseSocketsHttpHandler 开关:By defining the System.Net.Http.UseSocketsHttpHandler switch in the .netcore.runtimeconfig.json configuration file:

    "runtimeOptions": {
      "configProperties": {
          "System.Net.Http.UseSocketsHttpHandler": false
      }
    }
    
  • 通过定义名为 DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER 的环境变量,并将其设置为 false 或0。By defining an environment variable named DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER and setting it to either false or 0.

构造函数

HttpClientHandler()

创建 HttpClientHandler 类的实例。Creates an instance of a HttpClientHandler class.

属性

AllowAutoRedirect

获取或设置一个值,该值指示处理程序是否应遵循重定向响应。Gets or sets a value that indicates whether the handler should follow redirection responses.

AutomaticDecompression

获取或设置处理程序用于自动解压缩 HTTP 内容响应的解压缩方法类型。Gets or sets the type of decompression method used by the handler for automatic decompression of the HTTP content response.

CheckCertificateRevocationList

获取或设置一个值,该值指示是否根据证书颁发机构吊销列表检查证书。Gets or sets a value that indicates whether the certificate is checked against the certificate authority revocation list.

ClientCertificateOptions

获取或设置一个值,该值指示是否从证书存储自动挑选证书,或者是否允许调用方通过特定的客户端证书。Gets or sets a value that indicates if the certificate is automatically picked from the certificate store or if the caller is allowed to pass in a specific client certificate.

ClientCertificates

获取与对服务器的请求相关联的安全证书集合。Gets the collection of security certificates that are associated requests to the server.

CookieContainer

获取或设置处理程序用于存储服务器 Cookie 的 Cookie 容器。Gets or sets the cookie container used to store server cookies by the handler.

Credentials

获取或设置此处理程序所使用的身份验证信息。Gets or sets authentication information used by this handler.

DangerousAcceptAnyServerCertificateValidator

获取始终返回 true 的缓存委托。Gets a cached delegate that always returns true.

DefaultProxyCredentials

使用默认(系统)代理时,获取或设置要提交到默认代理服务器进行身份验证的凭据。When the default (system) proxy is being used, gets or sets the credentials to submit to the default proxy server for authentication. 只有在 UseProxy 设置为 trueProxy 设置为 null 时才使用默认代理。The default proxy is used only when UseProxy is set to true and Proxy is set to null.

MaxAutomaticRedirections

获取或设置处理程序遵循的最大重定向次数。Gets or sets the maximum number of redirects that the handler follows.

MaxConnectionsPerServer

获取或设置使用 HttpClient 对象发出请求时允许的最大并发连接数(每个服务器终结点)。Gets or sets the maximum number of concurrent connections (per server endpoint) allowed when making requests using an HttpClient object. 请注意,该限制针对每个服务器终结点,例如,值为 256 表示允许 256 个到 http://www.adatum.com/ 的并发连接,以及另外 256 个到 http://www.adventure-works.com/ 的并发连接。Note that the limit is per server endpoint, so for example a value of 256 would permit 256 concurrent connections to http://www.adatum.com/ and another 256 to http://www.adventure-works.com/.

MaxRequestContentBufferSize

获取或设置处理程序使用的最大请求内容缓冲区大小。Gets or sets the maximum request content buffer size used by the handler.

MaxResponseHeadersLength

获取或设置响应标头的最大长度,以千字节(1024 字节)为单位。Gets or sets the maximum length, in kilobytes (1024 bytes), of the response headers. 例如,如果该值为 64,那么允许的最大响应标头长度为 65536 字节。For example, if the value is 64, then 65536 bytes are allowed for the maximum response headers' length.

PreAuthenticate

获取或设置一个值,该值指示处理程序是否将授权标头与请求一起发送。Gets or sets a value that indicates whether the handler sends an Authorization header with the request.

Properties

获取 HttpClient 的自定义属性的可写字典(即地图)。Gets a writable dictionary (that is, a map) of custom properties for the HttpClient requests. 初始字典为空;可以为自定义处理程序和特殊处理插入和查询键值对。The dictionary is initialized empty; you can insert and query key-value pairs for your custom handlers and special processing.

Proxy

获取或设置此处理程序所使用的代理信息。Gets or sets proxy information used by the handler.

ServerCertificateCustomValidationCallback

获取或设置用于验证服务器证书的回调方法。Gets or sets a callback method to validate the server certificate.

SslProtocols

获取或设置 HttpClientHandler 对象管理的 HttpClient 对象所用的 TLS/SSL 协议。Gets or sets the TLS/SSL protocol used by the HttpClient objects managed by the HttpClientHandler object.

SupportsAutomaticDecompression

获取一个值,该值指示处理程序是否支持自动响应内容解压缩。Gets a value that indicates whether the handler supports automatic response content decompression.

SupportsProxy

获取一个指示处理程序是否支持代理设置的值。Gets a value that indicates whether the handler supports proxy settings.

SupportsRedirectConfiguration

获取一个值,该值表示处理程序是否支持 AllowAutoRedirectMaxAutomaticRedirections 属性的配置设置。Gets a value that indicates whether the handler supports configuration settings for the AllowAutoRedirect and MaxAutomaticRedirections properties.

UseCookies

获取或设置一个值,该值指示处理程序是否使用 CookieContainer 属性来存储服务器 Cookie 并在发送请求时使用这些 Cookie。Gets or sets a value that indicates whether the handler uses the CookieContainer property to store server cookies and uses these cookies when sending requests.

UseDefaultCredentials

获取或设置指示处理程序是否与请求一起发送默认凭据的值。Gets or sets a value that controls whether default credentials are sent with requests by the handler.

UseProxy

获取或设置一个值,该值指示处理程序是否对请求使用代理。Gets or sets a value that indicates whether the handler uses a proxy for requests.

方法

Dispose()

释放由 HttpMessageHandler 使用的非托管资源和托管资源。Releases the unmanaged resources and disposes of the managed resources used by the HttpMessageHandler.

(继承自 HttpMessageHandler)
Dispose(Boolean)

释放由 HttpClientHandler 使用的非托管资源,并可根据需要释放托管资源。Releases the unmanaged resources used by the HttpClientHandler and optionally disposes of the managed resources.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
SendAsync(HttpRequestMessage, CancellationToken)

基于作为不会阻止的操作在 HttpResponseMessage 中提供的信息创建 HttpRequestMessage 的实例。Creates an instance of HttpResponseMessage based on the information provided in the HttpRequestMessage as an operation that will not block.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅