HttpClient One-Pager
Introduction
-
The
HttpClientclass sends http requests and receives http responses from a Uri. -
An
HttpClientobject instance is a collection of settings that is applied to all requests. -
Each object instance uses its own connection pool, which isolates its requests from the others.
HttpClient
-
The
HttpContenttype is used to represent an Http body and content headers. Use theHttpContentclass to specify the body of the request. It also represents the response body accessible on the HttpResponseMessage.Content property. See HttpContent -
Send an HttpPost request with a json body formatted as a string
-
Send an HttpPost request with a strongly typed object as Json
-
Send an HttpPut request with a json body formatted as a string
-
Send an HttpPut request with a strongly typed object as Json
-
Send an HttpPatch request with a json body formatted as a string
-
Send an HttpDelete request with a json body formatted as a string
-
The
Http Headrequest returns only the headers associated with a resource. A response to theHeadrequest does not return a body. Http Head -
The
Http Optionsrequest is used to identify which Http methods a server or endpoint supports. Http Options
HttpResponseMessage
-
The
HttpResponseMessagetype contains the HttpResponse. -
You can access the response body using the
Contentproperty. Handling valid Http Content responses
HttpRequestException
-
HttpRequestExceptionis thrown when an HttpRequest fails. Handling an HttpRequestException
HttpProxy
-
A proxy can be configured in 2 ways.
-
A default is specified on the
HttpClient.DefaultProxyproperty. -
Or you can specify the
HttpClientHandler.Proxyproperty.
-
-
The
HttpClient.DefaultProxyis a static property that determines the default proxy that allHttpClientinstances use. See Global default proxy
IHttpClientFactory
-
IHttpClientFactoryserves as an abstraction that can createHttpClientinstances with custom configurations. -
If your app uses cookies then it is better to avoid
IHttpClientFactory. -
Use
IHttpClientFactoryfor short-lived clients. UsePooledConnectionLifetimefor long-lived clients. -
To regiser
IHttpClientFactory, callAddHttpClient. See Basic Usage -
Use named clients, if your app needs to connect to multiple services. See Named Clients
-
Typed clients are the same as named clients but without the use of strings. Probably better to use this. See Typed Clients
-
Get, post, put method calls are no different from
HttpClient. See Get, Post, Put
HttpClient lifetime Management
-
IHttpClientFactorycreates a new instance ofHttpClientfor every call toCreateClient. -
One
HttpClientHandleris created per client name. -
The factory manages the lifetimes of the
HttpClientHandlerinstances. -
To reduce resource consumption,
IHttpClientFactorycachesHttpClientHandlerinstances. -
An
HttpClientHandlerinstance may be reused from the cache if its lifetime has not expired. -
Caching of handlers is desirable as each handler manages its own underlying connection pool.
-
Creating more handlers may lead to socket exhaustion and connection delays.
-
Some handlers may also keep the connection open indefinitely, which can prevent the handler reacting to DNS changes.
-
The default handler lifetime is two minutes.
-
You can change the lifetime value. see HttpClient Lifetime Management.
SocketsHttpHandler
-
The
SocketsHttpHandlerimplementation ofHttpMessageHandlerallowsPooledConnectionLifetimeto be configured. -
This setting is used to ensure that the handler reacts to DNS changes, so using
SocketsHttpHandleris an alternative to usingIHttpClientFactory. -
IHttpClientFactoryandSocketsHttpHandlercan be used together. See the details
Use named clients in singleton service.
-
With named clients,
IHttpClientFactoryis injected into services, a newHttpClientis created everytimeCreateClientis called. -
Typed clients are transient objects usually injected into services. Typed clients are supposed to be short-lived. Singleton services are supposed to be long-lived. See the problem there.
Message Handler DI Scope
-
IHttpClientFactorycreates a seperate DI scope per eachHttpMessageHandlerinstance. -
They are separate from application DI scope like aspnetcore request scope or user-created manual DI scope.
-
HttpMessageHandler scopes can outlive application scopes.
-
Do not cache scope related information inside HttpMessageHandler instances.
-
Generally avoid such code gymnastics. Use this section more like an fyi.
Guidelines for using HttpClient
-
If a DNS entry changes regularly, the client wont respect those updates. Limit the lifetime of the connection by setting the PooledConnectionLifetime property, so that DNS lookup is repeated when the connection is replaced. For more information
-
To avoid port exhaustion problems, reusing
HttpClientinstance for as many Http requests as possible is recommended. Recommended usage
Rate limit an Http handler
-
To use rate limiting in .Net, add a reference to
System.Threading.RateLimitingnuget package. -
There is now a rate limiting middleware option. In case there is a rate limiting requirment for your application, click here for a sample implementation of how to set it up.
Http/3 support
-
In case, you really want to use Http/3. I would not recommend using it at this point of time.