Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions Kampute.HttpClient.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34018.315
# Visual Studio Version 18
VisualStudioVersion = 18.10.12224.181 stable
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{095A6455-3193-45A8-95F1-CC283E760B8D}"
ProjectSection(SolutionItems) = preProject
Expand All @@ -28,6 +28,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Kampute.HttpClient.Newtonso
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Kampute.HttpClient.NewtonsoftJson.Test", "tests\Kampute.HttpClient.NewtonsoftJson.Test\Kampute.HttpClient.NewtonsoftJson.Test.csproj", "{57C3C6E3-BEF0-4122-814F-D5566F4AE8CE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kampute.HttpClient.NetFramework.Test", "tests\Kampute.HttpClient.NetFramework.Test\Kampute.HttpClient.NetFramework.Test.csproj", "{25DA709C-5440-C3FD-852E-1CE90A21F521}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -122,6 +124,18 @@ Global
{57C3C6E3-BEF0-4122-814F-D5566F4AE8CE}.Release|x64.Build.0 = Release|Any CPU
{57C3C6E3-BEF0-4122-814F-D5566F4AE8CE}.Release|x86.ActiveCfg = Release|Any CPU
{57C3C6E3-BEF0-4122-814F-D5566F4AE8CE}.Release|x86.Build.0 = Release|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Debug|Any CPU.Build.0 = Debug|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Debug|x64.ActiveCfg = Debug|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Debug|x64.Build.0 = Debug|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Debug|x86.ActiveCfg = Debug|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Debug|x86.Build.0 = Debug|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Release|Any CPU.ActiveCfg = Release|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Release|Any CPU.Build.0 = Release|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Release|x64.ActiveCfg = Release|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Release|x64.Build.0 = Release|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Release|x86.ActiveCfg = Release|Any CPU
{25DA709C-5440-C3FD-852E-1CE90A21F521}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
15 changes: 14 additions & 1 deletion docs/client-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,27 @@ See [Getting started](getting-started.md) for package installation. Replace the

## HttpClient Lifetime

By default, [`HttpRestClient`](~/api/Kampute.HttpClient.HttpRestClient.html) acquires a shared [`HttpClient`](https://learn.microsoft.com/dotnet/api/system.net.http.httpclient) instance. This avoids creating a new connection pool for every short-lived client wrapper.
By default, [`HttpRestClient`](~/api/Kampute.HttpClient.HttpRestClient.html) acquires a shared [`HttpClient`](https://learn.microsoft.com/dotnet/api/system.net.http.httpclient) instance, so clients that exist at the same time use one connection pool instead of one each. The shared instance is disposed when the last client that uses it is disposed, and the next client creates a new one, so keep a client for as long as you call the API rather than creating one per call.

```csharp
using Kampute.HttpClient;

using var client = new HttpRestClient();
```

An `HttpClient` resolves a host name only when it opens a connection, and it reuses open connections, so a long-lived shared instance does not follow DNS changes. On .NET Core and .NET 5 or later, set [`SharedHttpClient.Factory`](~/api/Kampute.HttpClient.Utilities.SharedHttpClient.html#Kampute_HttpClient_Utilities_SharedHttpClient_Factory) at startup, before the first client is created, to give the shared instance a [`SocketsHttpHandler`](https://learn.microsoft.com/dotnet/api/system.net.http.socketshttphandler) with a [`PooledConnectionLifetime`](https://learn.microsoft.com/dotnet/api/system.net.http.socketshttphandler.pooledconnectionlifetime). Connections older than that are replaced, and the host name is resolved again. Choose the interval from how often the DNS entries of your API change.

```csharp
using System;
using System.Net.Http;
using Kampute.HttpClient.Utilities;

SharedHttpClient.Factory = () => new HttpClient(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(15)
});
```

If your application already manages [`HttpClient`](https://learn.microsoft.com/dotnet/api/system.net.http.httpclient) instances, pass one in directly. This is useful when you configure handlers, proxies, default timeouts, or dependency-injection lifetimes elsewhere.

```csharp
Expand Down
4 changes: 2 additions & 2 deletions docs/content-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ The base package registers no content formatter. Each format registers its forma

## JSON

Both JSON formatters read `application/json`, `application/problem+json`, and any other media type with the `+json` suffix, such as `application/vnd.example+json`, and write `application/json`. Install either JSON package as described in [Getting started](getting-started.md). Pass serializer options when registering the formatter:
Both JSON formatters read `application/json` and any media type with the `+json` suffix, such as `application/vnd.example+json`, and write `application/json`. Install either JSON package as described in [Getting started](getting-started.md). Pass serializer options when registering the formatter:

```csharp
using System.Text.Json;
Expand All @@ -28,7 +28,7 @@ For [`Newtonsoft.Json`](https://www.newtonsoft.com/json/help/html/N_Newtonsoft_J

## XML

[`UseXml()`](~/api/Kampute.HttpClient.Xml.HttpRestClientXmlExtensions.html#Kampute_HttpClient_Xml_HttpRestClientXmlExtensions_UseXml_Kampute_HttpClient_HttpRestClient_System_Action{Kampute_HttpClient_Xml_XmlFormatter}_) registers an [`XmlFormatter`](~/api/Kampute.HttpClient.Xml.XmlFormatter.html), which reads `application/xml`, `text/xml`, `application/problem+xml`, and any other media type with the `+xml` suffix, and writes `application/xml`. Its [`Serializer`](~/api/Kampute.HttpClient.Xml.XmlFormatter.html#Kampute_HttpClient_Xml_XmlFormatter_Serializer) setting chooses the serializer. With the default, [`XmlSerializerKind.Auto`](~/api/Kampute.HttpClient.Xml.XmlSerializerKind.html#fields), types marked with [`[DataContract]`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.datacontractattribute) or [`[CollectionDataContract]`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.collectiondatacontractattribute) use [`DataContractSerializer`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.datacontractserializer), and all other types use [`XmlSerializer`](https://learn.microsoft.com/dotnet/api/system.xml.serialization.xmlserializer). The rule applies to responses by the requested type and to payloads by their runtime type. Set [`XmlSerializerKind.XmlSerializer`](~/api/Kampute.HttpClient.Xml.XmlSerializerKind.html#fields) or [`XmlSerializerKind.DataContractSerializer`](~/api/Kampute.HttpClient.Xml.XmlSerializerKind.html#fields) to use one serializer for every type, and [`DataContractSettings`](~/api/Kampute.HttpClient.Xml.XmlFormatter.html#Kampute_HttpClient_Xml_XmlFormatter_DataContractSettings) to configure [`DataContractSerializer`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.datacontractserializer).
[`UseXml()`](~/api/Kampute.HttpClient.Xml.HttpRestClientXmlExtensions.html#Kampute_HttpClient_Xml_HttpRestClientXmlExtensions_UseXml_Kampute_HttpClient_HttpRestClient_System_Action{Kampute_HttpClient_Xml_XmlFormatter}_) registers an [`XmlFormatter`](~/api/Kampute.HttpClient.Xml.XmlFormatter.html), which reads `application/xml`, `text/xml`, and any media type with the `+xml` suffix, and writes `application/xml`. Its [`Serializer`](~/api/Kampute.HttpClient.Xml.XmlFormatter.html#Kampute_HttpClient_Xml_XmlFormatter_Serializer) setting chooses the serializer. With the default, [`XmlSerializerKind.Auto`](~/api/Kampute.HttpClient.Xml.XmlSerializerKind.html#fields), types marked with [`[DataContract]`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.datacontractattribute) or [`[CollectionDataContract]`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.collectiondatacontractattribute) use [`DataContractSerializer`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.datacontractserializer), and all other types use [`XmlSerializer`](https://learn.microsoft.com/dotnet/api/system.xml.serialization.xmlserializer). The rule applies to responses by the requested type and to payloads by their runtime type. Set [`XmlSerializerKind.XmlSerializer`](~/api/Kampute.HttpClient.Xml.XmlSerializerKind.html#fields) or [`XmlSerializerKind.DataContractSerializer`](~/api/Kampute.HttpClient.Xml.XmlSerializerKind.html#fields) to use one serializer for every type, and [`DataContractSettings`](~/api/Kampute.HttpClient.Xml.XmlFormatter.html#Kampute_HttpClient_Xml_XmlFormatter_DataContractSettings) to configure [`DataContractSerializer`](https://learn.microsoft.com/dotnet/api/system.runtime.serialization.datacontractserializer).

The following POST writes to your API; `Resource` is your application's serializable model.

Expand Down
4 changes: 2 additions & 2 deletions docs/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A request can fail in two ways: without a response, such as when the connection

## Retry Connection Failures

A request that fails without a response, because the connection is refused or reset, the host cannot be reached, or [`HttpClient.Timeout`](https://learn.microsoft.com/dotnet/api/system.net.http.httpclient.timeout) elapses, is retried only if you set [`RetryPolicy`](~/api/Kampute.HttpClient.HttpRestClient.html#Kampute_HttpClient_HttpRestClient_RetryPolicy). The default, [`HttpRetryPolicy.None`](~/api/Kampute.HttpClient.HttpRetryPolicy.html#Kampute_HttpClient_HttpRetryPolicy_None), does not retry.
A request that fails without a response, because the connection is refused, reset, or closed before the response is complete, the host name cannot be resolved or the host cannot be reached, or [`HttpClient.Timeout`](https://learn.microsoft.com/dotnet/api/system.net.http.httpclient.timeout) elapses, is retried only if you set [`RetryPolicy`](~/api/Kampute.HttpClient.HttpRestClient.html#Kampute_HttpClient_HttpRestClient_RetryPolicy). The default, [`HttpRetryPolicy.None`](~/api/Kampute.HttpClient.HttpRetryPolicy.html#Kampute_HttpClient_HttpRetryPolicy_None), does not retry.

```csharp
using System;
Expand All @@ -27,7 +27,7 @@ The retry strategy comes from the [`Kampute.Resilience`](https://kampute.github.

## Structured Error Bodies

Set [`ResponseErrorType`](~/api/Kampute.HttpClient.HttpRestClient.html#Kampute_HttpClient_HttpRestClient_ResponseErrorType) to your API's error model. Register a [content formatter](content-formats.md) that can read that model from the response media type. The JSON and XML formatters also read RFC 9457 problem details, `application/problem+json` and `application/problem+xml`, so an error model with the problem details fields works with them.
Set [`ResponseErrorType`](~/api/Kampute.HttpClient.HttpRestClient.html#Kampute_HttpClient_HttpRestClient_ResponseErrorType) to your API's error model. Register a [content formatter](content-formats.md) that can read that model from the response media type.

The deserialized model is available through [`HttpResponseException.ResponseObject`](~/api/Kampute.HttpClient.HttpResponseException.html#Kampute_HttpClient_HttpResponseException_ResponseObject). If the model implements [`IHttpErrorResponse`](~/api/Kampute.HttpClient.Interfaces.IHttpErrorResponse.html), its [`ToException()`](~/api/Kampute.HttpClient.Interfaces.IHttpErrorResponse.html#Kampute_HttpClient_Interfaces_IHttpErrorResponse_ToException_System_Net_HttpStatusCode_) method constructs the exception. See the reference for the full error-response contract.

Expand Down
7 changes: 3 additions & 4 deletions src/Kampute.HttpClient.Json/JsonFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ namespace Kampute.HttpClient.Json
/// </summary>
/// <remarks>
/// <para>
/// The formatter also reads <c>application/problem+json</c>, the problem details format of RFC 9457 for error responses, and advertises it in
/// the <c>Accept</c> header. It reads any other media type with the <c>+json</c> structured syntax suffix, which RFC 6839 permits for media
/// types whose representation follows <c>application/json</c>, such as <c>application/vnd.example+json</c>, but does not advertise it. It writes
/// The formatter also reads any media type with the <c>+json</c> structured syntax suffix, which RFC 6839 permits for media types whose
/// representation follows <c>application/json</c>, such as <c>application/vnd.example+json</c>, but does not advertise it. It writes
/// <c>application/json</c> only.
/// </para>
/// <para>
Expand All @@ -39,7 +38,7 @@ public sealed class JsonFormatter : HttpContentFormatter
/// Initializes a new instance of the <see cref="JsonFormatter"/> class.
/// </summary>
public JsonFormatter()
: base([MediaTypeNames.Application.Json, MediaTypeNames.Application.ProblemJson], [MediaTypeNames.Application.Json])
: base([MediaTypeNames.Application.Json], [MediaTypeNames.Application.Json])
{
}

Expand Down
2 changes: 1 addition & 1 deletion src/Kampute.HttpClient.Json/Kampute.HttpClient.Json.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Title>Kampute.HttpClient.Json</Title>
<Description>This package is an extension package for Kampute.HttpClient, enhancing it to manage application/json content types, using System.Text.Json library for serialization and deserialization of JSON responses and payloads.</Description>
<Authors>Kambiz Khojasteh</Authors>
<Version>3.1.0</Version>
<Version>3.2.0</Version>
<Company>Kampute</Company>
<Copyright>Copyright (c) 2025 Kampute</Copyright>
<LangVersion>latest</LangVersion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Title>Kampute.HttpClient.NewtonsoftJson</Title>
<Description>This package is an extension package for Kampute.HttpClient, enhancing it to manage application/json content types, using Newtonsoft.Json library for serialization and deserialization of JSON responses and payloads.</Description>
<Authors>Kambiz Khojasteh</Authors>
<Version>3.1.0</Version>
<Version>3.2.0</Version>
<Company>Kampute</Company>
<Copyright>Copyright (c) 2025 Kampute</Copyright>
<LangVersion>latest</LangVersion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ namespace Kampute.HttpClient.NewtonsoftJson
/// </summary>
/// <remarks>
/// <para>
/// The formatter also reads <c>application/problem+json</c>, the problem details format of RFC 9457 for error responses, and advertises it in
/// the <c>Accept</c> header. It reads any other media type with the <c>+json</c> structured syntax suffix, which RFC 6839 permits for media
/// types whose representation follows <c>application/json</c>, such as <c>application/vnd.example+json</c>, but does not advertise it. It writes
/// The formatter also reads any media type with the <c>+json</c> structured syntax suffix, which RFC 6839 permits for media types whose
/// representation follows <c>application/json</c>, such as <c>application/vnd.example+json</c>, but does not advertise it. It writes
/// <c>application/json</c> only.
/// </para>
/// <para>
Expand All @@ -40,7 +39,7 @@ public sealed class NewtonsoftJsonFormatter : HttpContentFormatter
/// Initializes a new instance of the <see cref="NewtonsoftJsonFormatter"/> class.
/// </summary>
public NewtonsoftJsonFormatter()
: base([MediaTypeNames.Application.Json, MediaTypeNames.Application.ProblemJson], [MediaTypeNames.Application.Json])
: base([MediaTypeNames.Application.Json], [MediaTypeNames.Application.Json])
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
/// <remarks>
/// The content has the headers of the content it compresses, except <c>Content-Length</c> and <c>Content-MD5</c>, which describe the
/// uncompressed body. It adds its encoding to the <c>Content-Encoding</c> header, and its length is not known until it is sent, so it is sent
/// with chunked transfer encoding.
/// without a <c>Content-Length</c> header, which over HTTP/1.1 means chunked transfer encoding.
/// </remarks>
public abstract class CompressedContent : HttpContentDecorator
{
Expand Down
8 changes: 4 additions & 4 deletions src/Kampute.HttpClient/HttpRestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public HttpRestClient(HttpClient httpClient, bool disposeClient = true)
public Uri? BaseAddress
{
get => _baseAddress;
set => _baseAddress = value is null || value.AbsolutePath.EndsWith("/") ? value : new Uri(value, "/");
set => _baseAddress = value is null || value.AbsolutePath.EndsWith("/") ? value : new Uri(value.GetLeftPart(UriPartial.Path) + "/");
}

/// <summary>
Expand All @@ -165,9 +165,9 @@ public Uri? BaseAddress
/// </value>
/// <remarks>
/// <para>
/// The policy applies when a request fails without a response, for example because the connection is refused or reset, the host cannot be
/// reached, or <see cref="System.Net.Http.HttpClient.Timeout"/> elapses. Error responses, such as '503 Service Unavailable', are handled by
/// <see cref="ErrorHandlers"/> instead.
/// The policy applies when a request fails without a response, for example because the connection is refused, reset, or closed before the
/// response is complete, the host name cannot be resolved or the host cannot be reached, or <see cref="System.Net.Http.HttpClient.Timeout"/>
/// elapses. Error responses, such as '503 Service Unavailable', are handled by <see cref="ErrorHandlers"/> instead.
/// </para>
/// <para>
/// The limits of the policy apply to the retries after connection failures only. Error handlers count their own retries separately, so a
Expand Down
2 changes: 1 addition & 1 deletion src/Kampute.HttpClient/Kampute.HttpClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Title>Kampute.HttpClient</Title>
<Description>Kampute.HttpClient is a versatile and lightweight .NET library that simplifies RESTful API communication. Its core HttpRestClient class provides a streamlined approach to HTTP interactions, offering advanced features such as two-way content formatters with built-in XML support, robust error handling, configurable retry policies, and detailed request-response processing. Striking a balance between simplicity and extensibility, Kampute.HttpClient empowers developers with a powerful yet easy-to-use client for seamless API integration across a wide range of .NET applications.</Description>
<Authors>Kambiz Khojasteh</Authors>
<Version>3.1.0</Version>
<Version>3.2.0</Version>
<Company>Kampute</Company>
<Copyright>Copyright (c) 2025 Kampute</Copyright>
<LangVersion>latest</LangVersion>
Expand Down
Loading
Loading