HttpRestClient Class
- Namespace
- Kampute.HttpClient
- Assembly
- Kampute.HttpClient.dll
Definition
public class HttpRestClient : IDisposable- Inheritance
- object
- HttpRestClient
- Implements
Remarks
Constructors
HttpRestClient()
public HttpRestClient()Remarks
HttpRestClient(SharedDisposable<HttpClient>.Reference)
public HttpRestClient(SharedDisposable<HttpClient>.Reference httpClientReference)Parameters
httpClientReferenceSharedDisposable<HttpClient>.Reference- A reference to a shared HttpClient instance, managed as SharedDisposable<T>.Reference.
Exceptions
- ArgumentNullException
- Thrown if
httpClientReferenceisnull>.
Remarks
HttpRestClient(HttpClient, bool)
public HttpRestClient(HttpClient httpClient, bool disposeClient = true)Parameters
httpClientHttpClient- The HttpClient to be used by the HttpRestClient.
disposeClientbool optional- Specifies whether the HttpRestClient should dispose of the provided HttpClient when the HttpRestClient is disposed.
Exceptions
- ArgumentNullException
- Thrown if
httpClientisnull.
Properties
BackoffStrategy
public IHttpBackoffProvider BackoffStrategy { get; set; }Property Value
- IHttpBackoffProvider
- The backoff strategy for handling transient connection failures during HTTP requests.
Remarks
BaseAddress
public Uri BaseAddress { get; set; }Property Value
- Uri
- The base address for HTTP requests.
Remarks
If the provided base address does not end with a slash, one is automatically appended. The presence or absence of this trailing slash is significant in how relative URLs are resolved. For instance, if the base address is http://example.com/api (no trailing slash) and the relative URL is "users", the resolved URL will be http://example.com/users. Conversely, if the base address ends with a slash, like http://example.com/api/, the resolved URL will be http://example.com/api/users. This subtle difference can be crucial in ensuring requests are routed correctly.
It's also worth noting that a null value for the base address is acceptable and indicates that no base address is set. In such cases, any HTTP request must use an absolute URL.
DefaultRequestHeaders
public HttpRequestHeaders DefaultRequestHeaders { get; }Property Value
- HttpRequestHeaders
- The headers which should be sent with each request.
ErrorHandlers
public HttpErrorHandlerCollection ErrorHandlers { get; }Property Value
- HttpErrorHandlerCollection
- The mutable collection of HTTP error handlers used for handling error responses.
Remarks
ResponseDeserializers
public HttpContentDeserializerCollection ResponseDeserializers { get; }Property Value
- HttpContentDeserializerCollection
- The mutable collection of HTTP content deserializers used for deserializing response content.
Remarks
ResponseErrorType
public Type ResponseErrorType { get; set; }Property Value
- Type
- The Type used to deserialize the response body when the response status code indicates an error.
Remarks
This property specifies the Type that the HttpRestClient will use to deserialize the response content in cases where the HTTP response indicates an error. It is important to ensure that the custom type specified is compatible with the expected error response format and can be deserialized by the content deserializers available to the HttpRestClient.
When the specified type implements the IHttpErrorResponse interface, the deserialized object is utilized to construct a more informative exception. This mechanism enables the integration of custom error handling strategies by leveraging structured error information returned from the server.
Methods
BeginHeaderScope(IEnumerable<KeyValuePair<string, string>>)
public virtual IDisposable BeginHeaderScope(IEnumerable<KeyValuePair<string, string>> headers)Parameters
headersIEnumerable<KeyValuePair<string, string>>- The request headers to be applied exclusively during the lifetime of the new scope.
Returns
- IDisposable
- An IDisposable representing the new scope. Disposing of this object will end the scope and revert changes in the request headers.
Exceptions
- ArgumentNullException
- Thrown if
headersisnull.
Remarks
This method creates a scope associated with the current HttpRestClient instance to add, modify or remove any request header in subsequent requests during the lifetime of this scope. To remove a header, use null for its value.
Any header modifications made within this scope take precedence over the client's default headers. Header adjustments by other active scopes are overridden by those provided in this scope. However, the default request headers set on the underlying HttpClient instance take precedence over the default and scoped headers of the HttpRestClient instance because they are applied later in the message handler pipeline. To avoid conflicts, it is recommended to keep the default request headers of the underlying HttpClient instance empty.
Upon disposing of the scope, all header adjustments are reverted, restoring the headers to their state before the scope was activated.
BeginPropertyScope(IEnumerable<KeyValuePair<string, object>>)
public virtual IDisposable BeginPropertyScope(IEnumerable<KeyValuePair<string, object>> properties)Parameters
propertiesIEnumerable<KeyValuePair<string, object>>- The request properties to be applied exclusively during the lifetime of the new scope.
Returns
- IDisposable
- An IDisposable representing the new scope. Disposing of this object will end the scope and revert changes in the request properties.
Exceptions
- ArgumentNullException
- Thrown if
propertiesisnull.
Remarks
This method creates a scope associated with the current HttpRestClient instance to add, modify or remove any request properties in subsequent requests during the lifetime of this scope. To remove a property, use null for its value.
Upon disposing of the scope, all property adjustments are reverted, restoring the properties to their state before the scope was activated.
CreateHttpRequest(HttpMethod, string, Type)
protected virtual HttpRequestMessage CreateHttpRequest(HttpMethod method, string uri, Type responseObjectType)Parameters
methodHttpMethod- The HTTP method to be used for the request, such as GET, POST, PUT, etc.
uristring- The URI to which the request will be sent. Should be a valid, fully qualified URL.
responseObjectTypeType- The type of the object expected to be contained in the response.
Returns
- HttpRequestMessage
- An HttpRequestMessage configured with the specified method and URI.
Exceptions
- ArgumentNullException
- Thrown if
methodoruriisnull.
Remarks
This method constructs a new HTTP request message by setting the HTTP method and URI. It prepares the request for transmission by configuring both the headers and custom properties appropriate for the given context and operation.
Headers are added or adjusted from both the default headers provided by the DefaultRequestHeaders property and any scoped headers that are active at the time of this request’s creation. Scoped headers are prioritized over default headers in case of key conflicts to ensure that context-specific modifications are respected.
If an Accept header is absent in both default and scoped headers, it is added based on the media types supported by the content deserializers for the specified responseObjectType. If responseObjectType is null, the header defaults to accepting all media types ("*/*").
This method also includes scoped properties in the HTTP request message to provide additional context and facilitate easier tracking and processing of the request. In addition to the scoped properties, the following properties are added:
- HttpRequestMessagePropertyKeys.TransactionId– A unique identifier (Guid) generated and assigned to each request, aiding in the request's tracking, debugging, and logging processes. The unique identifier ensures that each request can be individually tracked, even when multiple requests are executed simultaneously or when requests are retried due to transient failures.
- HttpRequestMessagePropertyKeys.ResponseObjectType– Defines the .NET type (Type) expected in the response, if any. This metadata provides context that can improve debugging, enhance logging details, and support error recovery strategies.
DecideOnRetryAsync(HttpRequestException, HttpRequestMessage, CancellationToken)
protected virtual Task<HttpErrorHandlerResult> DecideOnRetryAsync(HttpRequestException error, HttpRequestMessage request, CancellationToken cancellationToken)Parameters
errorHttpRequestException- The HttpRequestException encapsulating details of the encountered error during the HTTP request execution.
requestHttpRequestMessage- The HttpRequestMessage that led to the failed response.
cancellationTokenCancellationToken- A token for canceling the operation.
Returns
- Task<HttpErrorHandlerResult>
- A task that resolves to an HttpErrorHandlerResult, indicating whether to retry the request or that the error is unrecoverable.
Exceptions
- ArgumentNullException
- Thrown if
errororrequestisnull.
Remarks
See Also
DecideOnRetryAsync(HttpResponseException, HttpRequestMessage, HttpResponseMessage, CancellationToken)
protected virtual Task<HttpErrorHandlerResult> DecideOnRetryAsync(
HttpResponseException error,
HttpRequestMessage request,
HttpResponseMessage response,
CancellationToken cancellationToken)Parameters
errorHttpResponseException- The HttpResponseException encapsulating details of the encountered error during the HTTP request execution.
requestHttpRequestMessage- The HttpRequestMessage that led to the failed response.
responseHttpResponseMessage- The received HttpResponseMessage indicating a failure.
cancellationTokenCancellationToken- A token for canceling the operation.
Returns
- Task<HttpErrorHandlerResult>
- A task that resolves to an HttpErrorHandlerResult, indicating whether to retry the request or that the error is unrecoverable.
Exceptions
- ArgumentNullException
- Thrown if
error,requestorresponseisnull.
Remarks
See Also
DeserializeContentAsync(HttpResponseMessage, Type, CancellationToken)
protected virtual Task<object> DeserializeContentAsync(HttpResponseMessage response, Type objectType, CancellationToken cancellationToken)Parameters
responseHttpResponseMessage- The HttpResponseMessage to be read.
objectTypeType- The type of object to which the response body is to be converted.
cancellationTokenCancellationToken- A token for canceling the operation.
Returns
- Task<object>
- A task representing the asynchronous operation, with the deserialized response body as an object.
Exceptions
- ArgumentNullException
- Thrown if
responseorobjectTypeisnull. - HttpContentException
- Thrown when the response body is empty, the content type is unsupported, or parsing the response fails.
Remarks
See Also
DispatchAsync(HttpRequestMessage, CancellationToken)
protected virtual Task<HttpResponseMessage> DispatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)Parameters
requestHttpRequestMessage- The HttpRequestMessage to send.
cancellationTokenCancellationToken- A token for canceling the request.
Returns
- Task<HttpResponseMessage>
- A task that represents the asynchronous operation, with a result of the HttpResponseMessage received in response to the request.
Exceptions
- HttpResponseException
- Thrown if the response status code indicates a failure.
- HttpRequestException
- Thrown if the request fails due to an underlying issue such as network connectivity, DNS failure, server certificate validation, or timeout.
- OperationCanceledException
- Thrown if the operation is canceled via the cancellation token.
Remarks
DispatchWithRetriesAsync(HttpRequestMessage, CancellationToken)
protected virtual Task<HttpResponseMessage> DispatchWithRetriesAsync(HttpRequestMessage request, CancellationToken cancellationToken = default)Parameters
requestHttpRequestMessage- The HttpRequestMessage to send.
cancellationTokenCancellationToken optional- A token for canceling the request (optional).
Returns
- Task<HttpResponseMessage>
- A task that represents the asynchronous operation, with a result of the HttpResponseMessage received in response to the request.
Exceptions
- ArgumentNullException
- Thrown if
requestisnull. - HttpResponseException
- Thrown if the response status code indicates a failure.
- HttpRequestException
- Thrown if the request fails due to an underlying issue such as network connectivity, DNS failure, server certificate validation, or timeout.
- OperationCanceledException
- Thrown if the operation is canceled via the cancellation token.
Remarks
See Also
Dispose()
public void Dispose()Dispose(bool)
protected virtual void Dispose(bool disposing)Parameters
disposingbool- Indicates whether the method is called from a IDisposable.Dispose() method.
Finalize()
protected override void Finalize()OnAfterReceivingResponse(HttpResponseMessage)
protected virtual void OnAfterReceivingResponse(HttpResponseMessage response)Parameters
responseHttpResponseMessage- The HTTP response message that was received.
Remarks
OnBeforeSendingRequest(HttpRequestMessage)
protected virtual void OnBeforeSendingRequest(HttpRequestMessage request)Parameters
requestHttpRequestMessage- The HTTP request message that was created.
Remarks
OnDisposing()
protected virtual void OnDisposing()SendAsync<T>(HttpMethod, string, HttpContent, CancellationToken)
public virtual Task<T> SendAsync<T>(
HttpMethod method,
string uri,
HttpContent payload = null,
CancellationToken cancellationToken = default)Type Parameters
T- The type of the response object.
Parameters
methodHttpMethod- The HTTP method to use for the request.
uristring- The URI to which the request is sent.
payloadHttpContent optional- The HTTP request payload content (optional).
cancellationTokenCancellationToken optional- A token for canceling the request (optional).
Returns
- Task<T>
- A task that represents the asynchronous operation, with a result of the specified type.
Exceptions
- ArgumentNullException
- Thrown if
methodoruriisnull. - HttpResponseException
- Thrown if the response status code indicates a failure.
- HttpRequestException
- Thrown if the request fails due to an underlying issue such as network connectivity, DNS failure, server certificate validation, or timeout.
- HttpContentException
- Thrown if the response body is empty or its media type is not supported.
- OperationCanceledException
- Thrown if the operation is canceled via the cancellation token.
SendAsync(HttpMethod, string, HttpContent, CancellationToken)
public virtual Task<HttpResponseMessage> SendAsync(
HttpMethod method,
string uri,
HttpContent payload = null,
CancellationToken cancellationToken = default)Parameters
methodHttpMethod- The HTTP method to use for the request.
uristring- The URI to which the request is sent.
payloadHttpContent optional- The HTTP request payload content (optional).
cancellationTokenCancellationToken optional- A token for canceling the request (optional).
Returns
- Task<HttpResponseMessage>
- A task that represents the asynchronous operation. The task result contains the response.
Exceptions
- ArgumentNullException
- Thrown if
methodoruriisnull. - HttpResponseException
- Thrown if the response status code indicates a failure.
- HttpRequestException
- Thrown if the request fails due to an underlying issue such as network connectivity, DNS failure, server certificate validation, or timeout.
- OperationCanceledException
- Thrown if the operation is canceled via the cancellation token.
ToExceptionAsync(HttpResponseMessage, CancellationToken)
protected virtual Task<HttpResponseException> ToExceptionAsync(HttpResponseMessage response, CancellationToken cancellationToken)Parameters
responseHttpResponseMessage- The HTTP response message to convert.
cancellationTokenCancellationToken- A token for canceling the operation.
Returns
- Task<HttpResponseException>
- A task that represents the asynchronous operation. The task result contains an HttpResponseException object that represents the error extracted from the response.
Exceptions
- ArgumentNullException
- Thrown if
responseisnull.
Remarks
See Also
Events
AfterReceivingResponse
public event EventHandler<HttpResponseMessageEventArgs> AfterReceivingResponseEvent Type
Remarks
BeforeSendingRequest
public event EventHandler<HttpRequestMessageEventArgs> BeforeSendingRequestEvent Type
Remarks
Disposing
public event EventHandler<EventArgs> DisposingEvent Type
Remarks
Extension Methods
| DeleteAsync<T>(this HttpRestClient, string, CancellationToken) | Sends an asynchronous DELETE request to the specified URI and returns the response body deserialized as the specified type. |
| DeleteAsync(this HttpRestClient, string, CancellationToken) | Sends an asynchronous DELETE request to the specified URI without processing the response body. |
| DownloadAsync(this HttpRestClient, HttpMethod, string, HttpContent, Func<HttpContentHeaders, Stream>, CancellationToken) | Sends an asynchronous HTTP request with the specified method, URI, and payload, returning the response content as a stream. |
| GetAsByteArrayAsync(this HttpRestClient, string, CancellationToken) | Sends an asynchronous GET request to the specified URI and returns the response body as an array of bytes. |
| GetAsStreamAsync(this HttpRestClient, string, CancellationToken) | Sends an asynchronous GET request to the specified URI and returns the response body as a Stream. |
| GetAsStringAsync(this HttpRestClient, string, CancellationToken) | Sends an asynchronous GET request to the specified URI and returns the response body as a string. |
| GetAsync<T>(this HttpRestClient, string, CancellationToken) | Sends an asynchronous GET request to the specified URI and returns the response body deserialized as the specified type. |
| GetToStreamAsync(this HttpRestClient, string, Stream, CancellationToken) | Sends an asynchronous GET request to the specified URI and write the response body into the provided Stream. |
| HeadAsync(this HttpRestClient, string, CancellationToken) | Sends an asynchronous HEAD request to the specified URI and returns the response headers. |
| OptionsAsync(this HttpRestClient, string, CancellationToken) | Sends an asynchronous OPTIONS request to the specified URI and returns the response headers. |
| PatchAsFormAsync<T>(this HttpRestClient, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous PATCH request with URL-encoded form content to the specified URI and returns the response body deserialized as the specified type. |
| PatchAsFormAsync(this HttpRestClient, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous PATCH request with URL-encoded form content to the specified URI without processing the response body. |
| PatchAsync<T>(this HttpRestClient, string, HttpContent, CancellationToken) | Sends an asynchronous PATCH request to the specified URI and returns the response body deserialized as the specified type. |
| PatchAsync(this HttpRestClient, string, HttpContent, CancellationToken) | Sends an asynchronous PATCH request to the specified URI without processing the response body. |
| PostAsFormAsync<T>(this HttpRestClient, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous POST request with URL-encoded form content to the specified URI. |
| PostAsFormAsync(this HttpRestClient, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous POST request with URL-encoded form content to the specified URI without processing the response body. |
| PostAsync<T>(this HttpRestClient, string, HttpContent, CancellationToken) | Sends an asynchronous POST request to the specified URI and returns the response body deserialized as the specified type. |
| PostAsync(this HttpRestClient, string, HttpContent, CancellationToken) | Sends an asynchronous POST request to the specified URI without processing the response body. |
| PutAsFormAsync<T>(this HttpRestClient, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous PUT request with URL-encoded form content to the specified URI and returns the response body deserialized as the specified type. |
| PutAsFormAsync(this HttpRestClient, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous PUT request with URL-encoded form content to the specified URI without processing the response body. |
| PutAsync<T>(this HttpRestClient, string, HttpContent, CancellationToken) | Sends an asynchronous PUT request to the specified URI and returns the response body deserialized as the specified type. |
| PutAsync(this HttpRestClient, string, HttpContent, CancellationToken) | Sends an asynchronous PUT request to the specified URI without processing the response body. |
| SendAsFormAsync<T>(this HttpRestClient, HttpMethod, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous request with URL-encoded form content to the specified URI. |
| SendAsFormAsync(this HttpRestClient, HttpMethod, string, IEnumerable<KeyValuePair<string, string>>, CancellationToken) | Sends an asynchronous POST request with URL-encoded form content to the specified URI without processing the response body. |
| WithScope(this HttpRestClient) | Creates a new HttpRequestScope for managing scoped modifications of properties and headers for HTTP requests sent using the HttpRestClient. |

HttpRestClient abstracts the complexities of HttpClient, supporting the sharing of a single HttpClient instance across multiple HttpRestClient instances. This optimizes resource use and connection management, enhancing performance by reusing HTTP connections, especially during concurrent access to various services or API endpoints.
The client allows for scoped request headers and properties, providing temporary configurations that do not alter global settings. This ensures that changes remain isolated to specific contexts, increasing maintainability and reducing configuration errors during runtime.
It includes a ResponseDeserializers collection that automatically deserializes HTTP response content into .NET objects based on the response's
Content-Type. If theAcceptheader is not predefined, the client dynamically adjusts it based on the configured response deserializers and the expected .NET object type.Transient failures and network interruptions are managed via the BackoffStrategy property, which outlines retry logic and wait times between retries. This strategic approach helps avoid server overloads and improves communication success without excessive resource use.
Extensible error handling is enabled through the ErrorHandlers collection, allowing custom IHttpErrorHandler implementations to handle specific HTTP errors with tailored strategies.
Lifecycle events like BeforeSendingRequest and AfterReceivingResponse enhance request and response handling by enabling modifications, inspections, and logging, allowing for a highly customizable interaction.