HttpClientHandler HttpClientHandler HttpClientHandler HttpClientHandler Class

定义

.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
继承
HttpClientHandlerHttpClientHandlerHttpClientHandlerHttpClientHandler
派生

示例

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.1System.Net.Http.SocketsHttpHandler类而不是HttpClientHandler提供了使用的网络 Api 的更高级别的 HTTP 的实现。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. 可以配置应用程序以使用HttpClientHandler改为通过以下方式之一:You 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)
    

    通过定义System.Net.Http.useSocketsHttpHandler切入 。 netcore.runtimeconfig.json配置文件: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() HttpClientHandler() HttpClientHandler()

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

属性

AllowAutoRedirect AllowAutoRedirect AllowAutoRedirect AllowAutoRedirect

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

AutomaticDecompression AutomaticDecompression AutomaticDecompression AutomaticDecompression

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

CheckCertificateRevocationList CheckCertificateRevocationList CheckCertificateRevocationList CheckCertificateRevocationList

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

ClientCertificateOptions ClientCertificateOptions ClientCertificateOptions 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 ClientCertificates ClientCertificates ClientCertificates

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

CookieContainer CookieContainer CookieContainer CookieContainer

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

Credentials Credentials Credentials Credentials

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

DangerousAcceptAnyServerCertificateValidator DangerousAcceptAnyServerCertificateValidator DangerousAcceptAnyServerCertificateValidator DangerousAcceptAnyServerCertificateValidator

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

DefaultProxyCredentials DefaultProxyCredentials DefaultProxyCredentials 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 MaxAutomaticRedirections MaxAutomaticRedirections MaxAutomaticRedirections

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

MaxConnectionsPerServer MaxConnectionsPerServer MaxConnectionsPerServer 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 MaxRequestContentBufferSize MaxRequestContentBufferSize MaxRequestContentBufferSize

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

MaxResponseHeadersLength MaxResponseHeadersLength MaxResponseHeadersLength 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 PreAuthenticate PreAuthenticate PreAuthenticate

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

Properties Properties Properties 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 Proxy Proxy Proxy

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

ServerCertificateCustomValidationCallback ServerCertificateCustomValidationCallback ServerCertificateCustomValidationCallback ServerCertificateCustomValidationCallback

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

SslProtocols SslProtocols SslProtocols SslProtocols

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

SupportsAutomaticDecompression SupportsAutomaticDecompression SupportsAutomaticDecompression SupportsAutomaticDecompression

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

SupportsProxy SupportsProxy SupportsProxy SupportsProxy

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

SupportsRedirectConfiguration SupportsRedirectConfiguration SupportsRedirectConfiguration SupportsRedirectConfiguration

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

UseCookies UseCookies UseCookies 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 UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials

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

UseProxy UseProxy UseProxy UseProxy

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

方法

Dispose() Dispose() Dispose() Dispose()

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

(Inherited from HttpMessageHandler)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
SendAsync(HttpRequestMessage, CancellationToken) SendAsync(HttpRequestMessage, CancellationToken) SendAsync(HttpRequestMessage, CancellationToken) SendAsync(HttpRequestMessage, CancellationToken)

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

ToString() ToString() ToString() ToString()

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

(Inherited from Object)

适用于

另请参阅