From 8ac13bd07d2d727b5085aeeb5af572df32a0e418 Mon Sep 17 00:00:00 2001 From: Kambiz Date: Fri, 9 Oct 2026 06:29:20 +0800 Subject: [PATCH] Fix XML decoding, base address paths, and transient error detection * Stop advertising problem details media types The JSON and XML formatters no longer list application/problem+json and application/problem+xml among their readable media types, so the Accept header that the client builds no longer includes them. The formatters still read them through the +json and +xml suffix rules. The documentation no longer describes problem details, because the library has no specific support for them. * Decode XML responses as RFC 7303 specifies Without a charset parameter, XmlFormatter decoded the content as UTF-8 through a text reader, so the XML encoding declaration was ignored. A byte order mark now decides the encoding, then the charset parameter, then the encoding declaration, with UTF-8 as the default. * Keep the path of a base address without a trailing slash BaseAddress appended the slash by resolving "/" against the address, which replaces its path, so http://example.com/api became http://example.com/ instead of http://example.com/api/. * Recognize more transient network errors IsTransientNetworkError now also treats as transient: - An IOException, including HttpIOException, which reports a connection closed before the response was complete, unless it is an HTTP/2 or HTTP/3 protocol error. - A WebException of .NET Framework for a failed connection, send, or receive, a connection closed early, a failed host name resolution, or a timeout. - SocketError.Shutdown, which .NET on Unix reports for a write to a connection the peer closed, and AddressNotAvailable, NoBufferSpaceAvailable, and TooManyOpenSockets, which report exhausted local ports, buffers, or sockets. Every SocketError and WebExceptionStatus value is listed explicitly. Retries still do not depend on the request method. * Correct documentation - CompressedContent is sent with chunked transfer encoding only over HTTP/1.1. - The shared HttpClient is disposed with its last client, so clients share a connection pool only while they exist at the same time. - The user guide and SharedHttpClient.Factory explain how to make the shared HttpClient follow DNS changes with PooledConnectionLifetime. * Add tests for untested behavior Tests cover body parsing failures, cancellation while reading a body, unreadable error bodies, connection failures that are not retried, SharedHttpClient.Factory, a 401 handler that gets no new authorization, PerformAsync, and the ToString of HttpResponseException and HttpContentException. * Add the .NET Framework test project to the solution, and use collection expressions in test assertions --- Kampute.HttpClient.sln | 18 +- docs/client-configuration.md | 15 +- docs/content-formats.md | 4 +- docs/error-handling.md | 4 +- src/Kampute.HttpClient.Json/JsonFormatter.cs | 7 +- .../Kampute.HttpClient.Json.csproj | 2 +- .../Kampute.HttpClient.NewtonsoftJson.csproj | 2 +- .../NewtonsoftJsonFormatter.cs | 7 +- .../Abstracts/CompressedContent.cs | 2 +- src/Kampute.HttpClient/HttpRestClient.cs | 8 +- .../Kampute.HttpClient.csproj | 2 +- .../Utilities/ExceptionExtensions.cs | 188 +++++++++++++----- .../Utilities/SharedHttpClient.cs | 4 +- src/Kampute.HttpClient/Xml/XmlFormatter.cs | 15 +- .../Xml/XmlSerialization.cs | 11 +- .../JsonFormatterTests.cs | 4 +- ...ampute.HttpClient.NetFramework.Test.csproj | 1 + .../HttpRestClientJsonExtensionsTests.cs | 2 +- .../NewtonsoftJsonFormatterTests.cs | 4 +- .../Abstracts/HttpContentFormatterTests.cs | 6 +- .../DynamicHttpErrorHandlerTests.cs | 6 +- .../ErrorHandlers/HttpError401HandlerTests.cs | 24 +++ .../HttpContentExceptionTests.cs | 30 +++ .../HttpContentFormatterCollectionTests.cs | 2 +- .../HttpRequestScopeTests.cs | 23 +++ .../HttpResponseExceptionTests.cs | 22 ++ .../HttpRestClientTests.cs | 140 ++++++++++++- .../SendObjectTests.cs | 6 +- .../Utilities/ExceptionExtensionsTests.cs | 99 +++++++++ .../Xml/HttpRestClientXmlExtensionsTests.cs | 2 +- .../Xml/XmlFormatterTests.cs | 47 ++++- 31 files changed, 604 insertions(+), 103 deletions(-) create mode 100644 tests/Kampute.HttpClient.Test/HttpContentExceptionTests.cs create mode 100644 tests/Kampute.HttpClient.Test/Utilities/ExceptionExtensionsTests.cs diff --git a/Kampute.HttpClient.sln b/Kampute.HttpClient.sln index 2ba940d..77a5bca 100644 --- a/Kampute.HttpClient.sln +++ b/Kampute.HttpClient.sln @@ -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 @@ -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 @@ -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 diff --git a/docs/client-configuration.md b/docs/client-configuration.md index 5eddcb2..c3cec7c 100644 --- a/docs/client-configuration.md +++ b/docs/client-configuration.md @@ -9,7 +9,7 @@ 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; @@ -17,6 +17,19 @@ 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 diff --git a/docs/content-formats.md b/docs/content-formats.md index 51e95b4..b0ff796 100644 --- a/docs/content-formats.md +++ b/docs/content-formats.md @@ -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; @@ -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. diff --git a/docs/error-handling.md b/docs/error-handling.md index c304031..7e26eba 100644 --- a/docs/error-handling.md +++ b/docs/error-handling.md @@ -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; @@ -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. diff --git a/src/Kampute.HttpClient.Json/JsonFormatter.cs b/src/Kampute.HttpClient.Json/JsonFormatter.cs index cdfe631..97d9022 100644 --- a/src/Kampute.HttpClient.Json/JsonFormatter.cs +++ b/src/Kampute.HttpClient.Json/JsonFormatter.cs @@ -18,9 +18,8 @@ namespace Kampute.HttpClient.Json /// /// /// - /// The formatter also reads application/problem+json, the problem details format of RFC 9457 for error responses, and advertises it in - /// the Accept header. It reads any other media type with the +json structured syntax suffix, which RFC 6839 permits for media - /// types whose representation follows application/json, such as application/vnd.example+json, but does not advertise it. It writes + /// The formatter also reads any media type with the +json structured syntax suffix, which RFC 6839 permits for media types whose + /// representation follows application/json, such as application/vnd.example+json, but does not advertise it. It writes /// application/json only. /// /// @@ -39,7 +38,7 @@ public sealed class JsonFormatter : HttpContentFormatter /// Initializes a new instance of the class. /// public JsonFormatter() - : base([MediaTypeNames.Application.Json, MediaTypeNames.Application.ProblemJson], [MediaTypeNames.Application.Json]) + : base([MediaTypeNames.Application.Json], [MediaTypeNames.Application.Json]) { } diff --git a/src/Kampute.HttpClient.Json/Kampute.HttpClient.Json.csproj b/src/Kampute.HttpClient.Json/Kampute.HttpClient.Json.csproj index 3ee47ac..f05a1ce 100644 --- a/src/Kampute.HttpClient.Json/Kampute.HttpClient.Json.csproj +++ b/src/Kampute.HttpClient.Json/Kampute.HttpClient.Json.csproj @@ -5,7 +5,7 @@ Kampute.HttpClient.Json 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. Kambiz Khojasteh - 3.1.0 + 3.2.0 Kampute Copyright (c) 2025 Kampute latest diff --git a/src/Kampute.HttpClient.NewtonsoftJson/Kampute.HttpClient.NewtonsoftJson.csproj b/src/Kampute.HttpClient.NewtonsoftJson/Kampute.HttpClient.NewtonsoftJson.csproj index 1ca20b0..54cc778 100644 --- a/src/Kampute.HttpClient.NewtonsoftJson/Kampute.HttpClient.NewtonsoftJson.csproj +++ b/src/Kampute.HttpClient.NewtonsoftJson/Kampute.HttpClient.NewtonsoftJson.csproj @@ -5,7 +5,7 @@ Kampute.HttpClient.NewtonsoftJson 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. Kambiz Khojasteh - 3.1.0 + 3.2.0 Kampute Copyright (c) 2025 Kampute latest diff --git a/src/Kampute.HttpClient.NewtonsoftJson/NewtonsoftJsonFormatter.cs b/src/Kampute.HttpClient.NewtonsoftJson/NewtonsoftJsonFormatter.cs index 591858e..4a4f771 100644 --- a/src/Kampute.HttpClient.NewtonsoftJson/NewtonsoftJsonFormatter.cs +++ b/src/Kampute.HttpClient.NewtonsoftJson/NewtonsoftJsonFormatter.cs @@ -19,9 +19,8 @@ namespace Kampute.HttpClient.NewtonsoftJson /// /// /// - /// The formatter also reads application/problem+json, the problem details format of RFC 9457 for error responses, and advertises it in - /// the Accept header. It reads any other media type with the +json structured syntax suffix, which RFC 6839 permits for media - /// types whose representation follows application/json, such as application/vnd.example+json, but does not advertise it. It writes + /// The formatter also reads any media type with the +json structured syntax suffix, which RFC 6839 permits for media types whose + /// representation follows application/json, such as application/vnd.example+json, but does not advertise it. It writes /// application/json only. /// /// @@ -40,7 +39,7 @@ public sealed class NewtonsoftJsonFormatter : HttpContentFormatter /// Initializes a new instance of the class. /// public NewtonsoftJsonFormatter() - : base([MediaTypeNames.Application.Json, MediaTypeNames.Application.ProblemJson], [MediaTypeNames.Application.Json]) + : base([MediaTypeNames.Application.Json], [MediaTypeNames.Application.Json]) { } diff --git a/src/Kampute.HttpClient/Content/Compression/Abstracts/CompressedContent.cs b/src/Kampute.HttpClient/Content/Compression/Abstracts/CompressedContent.cs index 08e6926..c878fa1 100644 --- a/src/Kampute.HttpClient/Content/Compression/Abstracts/CompressedContent.cs +++ b/src/Kampute.HttpClient/Content/Compression/Abstracts/CompressedContent.cs @@ -13,7 +13,7 @@ /// /// The content has the headers of the content it compresses, except Content-Length and Content-MD5, which describe the /// uncompressed body. It adds its encoding to the Content-Encoding header, and its length is not known until it is sent, so it is sent - /// with chunked transfer encoding. + /// without a Content-Length header, which over HTTP/1.1 means chunked transfer encoding. /// public abstract class CompressedContent : HttpContentDecorator { diff --git a/src/Kampute.HttpClient/HttpRestClient.cs b/src/Kampute.HttpClient/HttpRestClient.cs index cd8354d..e91ab89 100644 --- a/src/Kampute.HttpClient/HttpRestClient.cs +++ b/src/Kampute.HttpClient/HttpRestClient.cs @@ -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) + "/"); } /// @@ -165,9 +165,9 @@ public Uri? BaseAddress /// /// /// - /// 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 elapses. Error responses, such as '503 Service Unavailable', are handled by - /// 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 + /// elapses. Error responses, such as '503 Service Unavailable', are handled by instead. /// /// /// The limits of the policy apply to the retries after connection failures only. Error handlers count their own retries separately, so a diff --git a/src/Kampute.HttpClient/Kampute.HttpClient.csproj b/src/Kampute.HttpClient/Kampute.HttpClient.csproj index b65a105..cc57b2d 100644 --- a/src/Kampute.HttpClient/Kampute.HttpClient.csproj +++ b/src/Kampute.HttpClient/Kampute.HttpClient.csproj @@ -5,7 +5,7 @@ Kampute.HttpClient 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. Kambiz Khojasteh - 3.1.0 + 3.2.0 Kampute Copyright (c) 2025 Kampute latest diff --git a/src/Kampute.HttpClient/Utilities/ExceptionExtensions.cs b/src/Kampute.HttpClient/Utilities/ExceptionExtensions.cs index 1657989..5a602bf 100644 --- a/src/Kampute.HttpClient/Utilities/ExceptionExtensions.cs +++ b/src/Kampute.HttpClient/Utilities/ExceptionExtensions.cs @@ -6,6 +6,11 @@ namespace Kampute.HttpClient.Utilities { using System; + using System.IO; + using System.Net; +#if !NETSTANDARD2_0 + using System.Net.Http; +#endif using System.Net.Sockets; /// @@ -18,59 +23,146 @@ public static class ExceptionExtensions /// /// The exception of a failed request. /// - /// if the innermost exception is a , or a - /// for a transient condition, such as a refused or reset connection or an unreachable host; otherwise, . + /// if the innermost exception reports a transient condition; otherwise, . The innermost exception + /// reports a transient condition if it is: + /// + /// A . + /// + /// + /// A for a condition that can clear by itself, such as a refused, reset, or aborted connection, an unreachable + /// host or network, a failed host name resolution, or a temporary lack of local sockets, ports, or buffer space. + /// + /// + /// + /// + /// An other than an HTTP/2 or HTTP/3 protocol error, which reports that the connection closed before the + /// response was complete. + /// + /// + /// + /// + /// A , which .NET Framework reports without a , for a failed connection, send, or + /// receive, a connection closed early, a failed host name resolution, or a timeout. + /// + /// + /// /// public static bool IsTransientNetworkError(this Exception exception) => exception.GetBaseException() switch { TimeoutException => true, - SocketException e => e.SocketErrorCode switch - { - SocketError.ConnectionAborted => true, - SocketError.ConnectionRefused => true, - SocketError.ConnectionReset => true, - SocketError.DestinationAddressRequired => false, - SocketError.Disconnecting => false, - SocketError.Fault => false, - SocketError.HostDown => true, - SocketError.HostNotFound => true, - SocketError.HostUnreachable => true, - SocketError.InProgress => false, - SocketError.Interrupted => true, - SocketError.InvalidArgument => false, - SocketError.IOPending => false, - SocketError.IsConnected => false, - SocketError.MessageSize => false, - SocketError.NetworkDown => true, - SocketError.NetworkReset => true, - SocketError.NetworkUnreachable => true, - SocketError.NoBufferSpaceAvailable => false, - SocketError.NoData => false, - SocketError.NoRecovery => false, - SocketError.NotConnected => true, - SocketError.NotInitialized => false, - SocketError.NotSocket => false, - SocketError.OperationAborted => true, - SocketError.OperationNotSupported => false, - SocketError.ProcessLimit => false, - SocketError.ProtocolFamilyNotSupported => false, - SocketError.ProtocolNotSupported => false, - SocketError.ProtocolOption => false, - SocketError.ProtocolType => false, - SocketError.Shutdown => false, - SocketError.SocketError => true, - SocketError.SocketNotSupported => false, - SocketError.Success => false, - SocketError.SystemNotReady => false, - SocketError.TimedOut => true, - SocketError.TooManyOpenSockets => false, - SocketError.TryAgain => true, - SocketError.TypeNotFound => false, - SocketError.VersionNotSupported => false, - SocketError.WouldBlock => false, - _ => false - }, + SocketException e => IsTransient(e.SocketErrorCode), + WebException e => IsTransient(e.Status), + IOException e => !IsHttpProtocolError(e), _ => false }; + + /// + /// Determines whether a socket error reports a condition that can clear by itself. + /// + /// The socket error to classify. + /// if is transient; otherwise, . + /// + /// On Unix, a write to a connection that the peer has closed (EPIPE) is reported as , and a connect + /// that finds no free ephemeral port (EADDRNOTAVAIL) as . + /// + private static bool IsTransient(SocketError socketError) => socketError switch + { + SocketError.AccessDenied => false, + SocketError.AddressAlreadyInUse => false, + SocketError.AddressFamilyNotSupported => false, + SocketError.AddressNotAvailable => true, + SocketError.AlreadyInProgress => false, + SocketError.ConnectionAborted => true, + SocketError.ConnectionRefused => true, + SocketError.ConnectionReset => true, + SocketError.DestinationAddressRequired => false, + SocketError.Disconnecting => false, + SocketError.Fault => false, + SocketError.HostDown => true, + SocketError.HostNotFound => true, + SocketError.HostUnreachable => true, + SocketError.InProgress => false, + SocketError.Interrupted => true, + SocketError.InvalidArgument => false, + SocketError.IOPending => false, + SocketError.IsConnected => false, + SocketError.MessageSize => false, + SocketError.NetworkDown => true, + SocketError.NetworkReset => true, + SocketError.NetworkUnreachable => true, + SocketError.NoBufferSpaceAvailable => true, + SocketError.NoData => false, + SocketError.NoRecovery => false, + SocketError.NotConnected => true, + SocketError.NotInitialized => false, + SocketError.NotSocket => false, + SocketError.OperationAborted => true, + SocketError.OperationNotSupported => false, + SocketError.ProcessLimit => false, + SocketError.ProtocolFamilyNotSupported => false, + SocketError.ProtocolNotSupported => false, + SocketError.ProtocolOption => false, + SocketError.ProtocolType => false, + SocketError.Shutdown => true, + SocketError.SocketError => true, + SocketError.SocketNotSupported => false, + SocketError.Success => false, + SocketError.SystemNotReady => false, + SocketError.TimedOut => true, + SocketError.TooManyOpenSockets => true, + SocketError.TryAgain => true, + SocketError.TypeNotFound => false, + SocketError.VersionNotSupported => false, + SocketError.WouldBlock => false, + _ => false + }; + + /// + /// Determines whether a status reports a condition that can clear by itself. + /// + /// The status to classify. + /// if is transient; otherwise, . + private static bool IsTransient(WebExceptionStatus status) => status switch + { + WebExceptionStatus.CacheEntryNotFound => false, + WebExceptionStatus.ConnectFailure => true, + WebExceptionStatus.ConnectionClosed => true, + WebExceptionStatus.KeepAliveFailure => true, + WebExceptionStatus.MessageLengthLimitExceeded => false, + WebExceptionStatus.NameResolutionFailure => true, + WebExceptionStatus.Pending => false, + WebExceptionStatus.PipelineFailure => true, + WebExceptionStatus.ProtocolError => false, + WebExceptionStatus.ProxyNameResolutionFailure => true, + WebExceptionStatus.ReceiveFailure => true, + WebExceptionStatus.RequestCanceled => false, + WebExceptionStatus.RequestProhibitedByCachePolicy => false, + WebExceptionStatus.RequestProhibitedByProxy => false, + WebExceptionStatus.SecureChannelFailure => false, + WebExceptionStatus.SendFailure => true, + WebExceptionStatus.ServerProtocolViolation => false, + WebExceptionStatus.Success => false, + WebExceptionStatus.Timeout => true, + WebExceptionStatus.TrustFailure => false, + WebExceptionStatus.UnknownError => false, + _ => false + }; + + /// + /// Determines whether an I/O exception reports an HTTP/2 or HTTP/3 protocol error. + /// + /// The exception to check. + /// if is an HttpProtocolException; otherwise, . + /// + /// HttpProtocolException exists on .NET 7 and later, so the netstandard2.0 build recognizes it by name. + /// + private static bool IsHttpProtocolError(IOException exception) + { +#if NETSTANDARD2_0 + return exception.GetType().FullName == "System.Net.Http.HttpProtocolException"; +#else + return exception is HttpProtocolException; +#endif + } } } diff --git a/src/Kampute.HttpClient/Utilities/SharedHttpClient.cs b/src/Kampute.HttpClient/Utilities/SharedHttpClient.cs index 6f0eecb..c9f1384 100644 --- a/src/Kampute.HttpClient/Utilities/SharedHttpClient.cs +++ b/src/Kampute.HttpClient/Utilities/SharedHttpClient.cs @@ -49,7 +49,9 @@ public static SharedDisposable.Reference AcquireReference() /// Thrown if the value is set after the first reference has been acquired. /// /// Set this property at application startup, before any is created with the shared , - /// to configure its handler, proxy, or timeout. + /// to configure its handler, proxy, or timeout. The shared is long-lived and resolves a host name only when it + /// opens a connection, so on .NET Core and .NET 5 or later, give it a SocketsHttpHandler with a PooledConnectionLifetime to + /// have it follow DNS changes. /// public static Func? Factory { diff --git a/src/Kampute.HttpClient/Xml/XmlFormatter.cs b/src/Kampute.HttpClient/Xml/XmlFormatter.cs index 3bc81b6..2dfa16f 100644 --- a/src/Kampute.HttpClient/Xml/XmlFormatter.cs +++ b/src/Kampute.HttpClient/Xml/XmlFormatter.cs @@ -9,7 +9,6 @@ namespace Kampute.HttpClient.Xml using System; using System.Net.Http; using System.Runtime.Serialization; - using System.Text; using System.Threading; using System.Threading.Tasks; @@ -18,10 +17,9 @@ namespace Kampute.HttpClient.Xml /// /// /// - /// The formatter also reads text/xml, which RFC 7303 registers with the same definition as application/xml, and - /// application/problem+xml, the problem details format of RFC 9457 for error responses, and advertises both in the Accept header. - /// It reads any other media type with the +xml structured syntax suffix, which RFC 7303 registers for XML media types, such as - /// application/vnd.example+xml, but does not advertise it. It writes application/xml only. + /// The formatter also reads text/xml, which RFC 7303 registers with the same definition as application/xml, and advertises it in + /// the Accept header. It reads any media type with the +xml structured syntax suffix, which RFC 7303 registers for XML media types, + /// such as application/vnd.example+xml, but does not advertise it. It writes application/xml only. /// /// /// The client reads a response with the first formatter in that can read it, so a formatter for a @@ -44,7 +42,7 @@ public sealed class XmlFormatter : HttpContentFormatter /// Initializes a new instance of the class. /// public XmlFormatter() - : base([MediaTypeNames.Application.Xml, MediaTypeNames.Text.Xml, MediaTypeNames.Application.ProblemXml], [MediaTypeNames.Application.Xml]) + : base([MediaTypeNames.Application.Xml, MediaTypeNames.Text.Xml], [MediaTypeNames.Application.Xml]) { } @@ -86,11 +84,12 @@ protected override bool CanReadMediaType(string mediaType) /// A token for canceling the operation. /// A task that resolves to the object read from . /// - /// The content is decoded with the character set of its Content-Type header, or as UTF-8 if it has none. + /// As RFC 7303 specifies, a byte order mark decides the character encoding of the content. Without one, the charset parameter of its + /// Content-Type header decides it, and without either, the XML encoding declaration, or UTF-8 if there is none. /// protected override async Task ReadContentAsync(HttpContent content, Type modelType, CancellationToken cancellationToken) { - var encoding = content.FindCharacterEncoding() ?? Encoding.UTF8; + var encoding = content.FindCharacterEncoding(); using var stream = await content.ReadAsStreamAsync().ConfigureAwait(false); return XmlSerialization.Read(stream, encoding, modelType, Serializer, DataContractSettings); } diff --git a/src/Kampute.HttpClient/Xml/XmlSerialization.cs b/src/Kampute.HttpClient/Xml/XmlSerialization.cs index 4b029fa..68224c8 100644 --- a/src/Kampute.HttpClient/Xml/XmlSerialization.cs +++ b/src/Kampute.HttpClient/Xml/XmlSerialization.cs @@ -34,15 +34,18 @@ internal static class XmlSerialization /// Reads an object of the specified type from a stream. /// /// The stream to read. - /// The character encoding of the stream. + /// + /// The character encoding named by the charset parameter of the content, which a byte order mark overrides, or + /// to detect the encoding from a byte order mark or the XML encoding declaration, with UTF-8 as the default. + /// /// The type of the object to read. /// The serializer choice. /// The settings of , if it is used. /// The object read from . - public static object? Read(Stream stream, Encoding encoding, Type type, XmlSerializerKind kind, DataContractSerializerSettings? dataContractSettings) + public static object? Read(Stream stream, Encoding? encoding, Type type, XmlSerializerKind kind, DataContractSerializerSettings? dataContractSettings) { - using var streamReader = new StreamReader(stream, encoding); - using var xmlReader = XmlReader.Create(streamReader); + using var streamReader = encoding is not null ? new StreamReader(stream, encoding) : null; + using var xmlReader = streamReader is not null ? XmlReader.Create(streamReader) : XmlReader.Create(stream); return UsesDataContract(kind, type) ? new DataContractSerializer(type, dataContractSettings).ReadObject(xmlReader) : new XmlSerializer(type).Deserialize(xmlReader); diff --git a/tests/Kampute.HttpClient.Json.Test/JsonFormatterTests.cs b/tests/Kampute.HttpClient.Json.Test/JsonFormatterTests.cs index 9119608..50065a7 100644 --- a/tests/Kampute.HttpClient.Json.Test/JsonFormatterTests.cs +++ b/tests/Kampute.HttpClient.Json.Test/JsonFormatterTests.cs @@ -15,8 +15,8 @@ public void MediaTypes_ReadJsonAndProblemJson_WriteJson() using (Assert.EnterMultipleScope()) { - Assert.That(formatter.GetReadableMediaTypes(typeof(TestModel)), Is.EqualTo(new[] { MediaTypeNames.Application.Json, MediaTypeNames.Application.ProblemJson })); - Assert.That(formatter.GetWritableMediaTypes(typeof(TestModel)), Is.EqualTo(new[] { MediaTypeNames.Application.Json })); + Assert.That(formatter.GetReadableMediaTypes(typeof(TestModel)), Is.EqualTo([MediaTypeNames.Application.Json])); + Assert.That(formatter.GetWritableMediaTypes(typeof(TestModel)), Is.EqualTo([MediaTypeNames.Application.Json])); Assert.That(formatter.CanRead(MediaTypeNames.Application.ProblemJson, typeof(TestModel)), Is.True); Assert.That(formatter.CanWrite(MediaTypeNames.Application.ProblemJson, typeof(TestModel)), Is.False); } diff --git a/tests/Kampute.HttpClient.NetFramework.Test/Kampute.HttpClient.NetFramework.Test.csproj b/tests/Kampute.HttpClient.NetFramework.Test/Kampute.HttpClient.NetFramework.Test.csproj index ec83e15..f6b2bb7 100644 --- a/tests/Kampute.HttpClient.NetFramework.Test/Kampute.HttpClient.NetFramework.Test.csproj +++ b/tests/Kampute.HttpClient.NetFramework.Test/Kampute.HttpClient.NetFramework.Test.csproj @@ -4,6 +4,7 @@ net48 false true + false latest enable 1701;1702;IDE0290;IDE0028 diff --git a/tests/Kampute.HttpClient.NewtonsoftJson.Test/HttpRestClientJsonExtensionsTests.cs b/tests/Kampute.HttpClient.NewtonsoftJson.Test/HttpRestClientJsonExtensionsTests.cs index 41dfce4..7c758e0 100644 --- a/tests/Kampute.HttpClient.NewtonsoftJson.Test/HttpRestClientJsonExtensionsTests.cs +++ b/tests/Kampute.HttpClient.NewtonsoftJson.Test/HttpRestClientJsonExtensionsTests.cs @@ -350,7 +350,7 @@ public async Task PostAsJsonAsync_WithBothJsonFormattersRegistered_EachPackageUs await Kampute.HttpClient.Json.HttpRestClientJsonExtensions.PostAsJsonAsync(client, "/models", payload); await client.PostAsJsonAsync("/models", payload); - Assert.That(sentBodies, Is.EqualTo(new[] { "{\"fullName\":\"JSON Test\"}", "{\"full_name\":\"JSON Test\"}" })); + Assert.That(sentBodies, Is.EqualTo(["{\"fullName\":\"JSON Test\"}", "{\"full_name\":\"JSON Test\"}"])); } } } diff --git a/tests/Kampute.HttpClient.NewtonsoftJson.Test/NewtonsoftJsonFormatterTests.cs b/tests/Kampute.HttpClient.NewtonsoftJson.Test/NewtonsoftJsonFormatterTests.cs index 3d095d9..6bc5fa4 100644 --- a/tests/Kampute.HttpClient.NewtonsoftJson.Test/NewtonsoftJsonFormatterTests.cs +++ b/tests/Kampute.HttpClient.NewtonsoftJson.Test/NewtonsoftJsonFormatterTests.cs @@ -15,8 +15,8 @@ public void MediaTypes_ReadJsonAndProblemJson_WriteJson() using (Assert.EnterMultipleScope()) { - Assert.That(formatter.GetReadableMediaTypes(typeof(TestModel)), Is.EqualTo(new[] { MediaTypeNames.Application.Json, MediaTypeNames.Application.ProblemJson })); - Assert.That(formatter.GetWritableMediaTypes(typeof(TestModel)), Is.EqualTo(new[] { MediaTypeNames.Application.Json })); + Assert.That(formatter.GetReadableMediaTypes(typeof(TestModel)), Is.EqualTo([MediaTypeNames.Application.Json])); + Assert.That(formatter.GetWritableMediaTypes(typeof(TestModel)), Is.EqualTo([MediaTypeNames.Application.Json])); Assert.That(formatter.CanRead(MediaTypeNames.Application.ProblemJson, typeof(TestModel)), Is.True); Assert.That(formatter.CanWrite(MediaTypeNames.Application.ProblemJson, typeof(TestModel)), Is.False); } diff --git a/tests/Kampute.HttpClient.Test/Content/Abstracts/HttpContentFormatterTests.cs b/tests/Kampute.HttpClient.Test/Content/Abstracts/HttpContentFormatterTests.cs index 7e43d84..e783cdb 100644 --- a/tests/Kampute.HttpClient.Test/Content/Abstracts/HttpContentFormatterTests.cs +++ b/tests/Kampute.HttpClient.Test/Content/Abstracts/HttpContentFormatterTests.cs @@ -17,9 +17,9 @@ public void MediaTypeQueries_HonorTheTypeFiltersAndIgnoreCase() using (Assert.EnterMultipleScope()) { - Assert.That(formatter.GetReadableMediaTypes(typeof(string)), Is.EqualTo(new[] { "text/x-read" })); + Assert.That(formatter.GetReadableMediaTypes(typeof(string)), Is.EqualTo(["text/x-read"])); Assert.That(formatter.GetReadableMediaTypes(typeof(int)), Is.Empty); - Assert.That(formatter.GetWritableMediaTypes(typeof(string)), Is.EqualTo(new[] { "text/x-write" })); + Assert.That(formatter.GetWritableMediaTypes(typeof(string)), Is.EqualTo(["text/x-write"])); Assert.That(formatter.GetWritableMediaTypes(typeof(int)), Is.Empty); Assert.That(formatter.CanRead("TEXT/X-READ", typeof(string)), Is.True); Assert.That(formatter.CanRead("text/x-write", typeof(string)), Is.False); @@ -50,7 +50,7 @@ public void CanRead_UsesCanReadMediaTypeButAdvertisesOnlyListedMediaTypes() Assert.That(formatter.CanRead("text/x-read", typeof(string)), Is.True); Assert.That(formatter.CanRead("application/vnd.example+test", typeof(string)), Is.True); Assert.That(formatter.CanRead("application/vnd.example+other", typeof(string)), Is.False); - Assert.That(formatter.GetReadableMediaTypes(typeof(string)), Is.EqualTo(new[] { "text/x-read" })); + Assert.That(formatter.GetReadableMediaTypes(typeof(string)), Is.EqualTo(["text/x-read"])); } } diff --git a/tests/Kampute.HttpClient.Test/ErrorHandlers/DynamicHttpErrorHandlerTests.cs b/tests/Kampute.HttpClient.Test/ErrorHandlers/DynamicHttpErrorHandlerTests.cs index 2036da8..4d87683 100644 --- a/tests/Kampute.HttpClient.Test/ErrorHandlers/DynamicHttpErrorHandlerTests.cs +++ b/tests/Kampute.HttpClient.Test/ErrorHandlers/DynamicHttpErrorHandlerTests.cs @@ -52,7 +52,7 @@ public async Task OnErrorResponse_InvokesDelegateWithResponseContext() using (Assert.EnterMultipleScope()) { Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Conflict)); - Assert.That(seenStatusCodes, Is.EqualTo(new[] { HttpStatusCode.Conflict })); + Assert.That(seenStatusCodes, Is.EqualTo([HttpStatusCode.Conflict])); } } @@ -103,7 +103,7 @@ public async Task OnErrorResponse_WithHandBuiltRetryRequestReusingOriginalConten using (Assert.EnterMultipleScope()) { Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); - Assert.That(sentBodies, Is.EqualTo(new[] { "original", "original", "original" })); + Assert.That(sentBodies, Is.EqualTo(["original", "original", "original"])); } } @@ -124,7 +124,7 @@ public async Task OnErrorResponse_WithHandBuiltRetryRequestWithNewContent_SendsN using (Assert.EnterMultipleScope()) { Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); - Assert.That(sentBodies, Is.EqualTo(new[] { "original", "replacement", "replacement" })); + Assert.That(sentBodies, Is.EqualTo(["original", "replacement", "replacement"])); } } diff --git a/tests/Kampute.HttpClient.Test/ErrorHandlers/HttpError401HandlerTests.cs b/tests/Kampute.HttpClient.Test/ErrorHandlers/HttpError401HandlerTests.cs index 81c6c83..be9c005 100644 --- a/tests/Kampute.HttpClient.Test/ErrorHandlers/HttpError401HandlerTests.cs +++ b/tests/Kampute.HttpClient.Test/ErrorHandlers/HttpError401HandlerTests.cs @@ -203,6 +203,30 @@ public async Task On401Response_ByFailedAuthentication_ThrowsUnauthorizedHttpErr Assert.That(caughtException.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); } + [Test] + public async Task On401Response_WhenAuthenticatorProvidesNoAuthorization_ThrowsUnauthorizedHttpErrorWithoutRetrying() + { + using var unauthorizeHandler = new HttpError401Handler((_, _) => Task.FromResult(null)); + + _client.ErrorHandlers.Add(unauthorizeHandler); + + var numberOfResponses = 0; + _mockMessageHandler.MockHttpResponse(request => + { + Interlocked.Increment(ref numberOfResponses); + return new HttpResponseMessage(HttpStatusCode.Unauthorized); + }); + + var exception = await Assert.ThrowsAsync(() => _client.SendAsync(HttpMethod.Get, "/protected/resource")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + Assert.That(numberOfResponses, Is.EqualTo(1)); + Assert.That(_client.DefaultRequestHeaders.Authorization, Is.Null); + } + } + [Test] public async Task On401Response_WithNonReusableContent_ThrowsUnauthorizedHttpErrorWithoutAuthenticating() { diff --git a/tests/Kampute.HttpClient.Test/HttpContentExceptionTests.cs b/tests/Kampute.HttpClient.Test/HttpContentExceptionTests.cs new file mode 100644 index 0000000..d057bbd --- /dev/null +++ b/tests/Kampute.HttpClient.Test/HttpContentExceptionTests.cs @@ -0,0 +1,30 @@ +namespace Kampute.HttpClient.Test +{ + using NUnit.Framework; + using System; + using System.Net.Http; + using System.Text; + + [TestFixture] + public class HttpContentExceptionTests + { + [Test] + public void ToString_IncludesContentTypeAndExpectedObjectType() + { + using var content = new StringContent("A,B", Encoding.UTF8, MediaTypeNames.Text.Csv); + var exception = new HttpContentException("Unreadable content") + { + Content = content, + ObjectType = typeof(Uri), + }; + + var text = exception.ToString(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(text, Does.Contain(MediaTypeNames.Text.Csv)); + Assert.That(text, Does.Contain(nameof(Uri))); + } + } + } +} diff --git a/tests/Kampute.HttpClient.Test/HttpContentFormatterCollectionTests.cs b/tests/Kampute.HttpClient.Test/HttpContentFormatterCollectionTests.cs index a2e1b26..d8bdc0a 100644 --- a/tests/Kampute.HttpClient.Test/HttpContentFormatterCollectionTests.cs +++ b/tests/Kampute.HttpClient.Test/HttpContentFormatterCollectionTests.cs @@ -350,7 +350,7 @@ public void GetAcceptableMediaTypes_WithSendOnlyFormatter_AddsNothing() var result = collection.GetAcceptableMediaTypes(typeof(string)); - Assert.That(result, Is.EqualTo(new[] { Constants.TestMediaType })); + Assert.That(result, Is.EqualTo([Constants.TestMediaType])); } [Test] diff --git a/tests/Kampute.HttpClient.Test/HttpRequestScopeTests.cs b/tests/Kampute.HttpClient.Test/HttpRequestScopeTests.cs index 0aced46..330b9d0 100644 --- a/tests/Kampute.HttpClient.Test/HttpRequestScopeTests.cs +++ b/tests/Kampute.HttpClient.Test/HttpRequestScopeTests.cs @@ -106,5 +106,28 @@ await _scope.PerformAsync(async client => await client.SendAsync(HttpMethod.Get, "/test"); }); } + + [Test] + public async Task PerformAsync_WithFunction_ReturnsResultAndAppliesScopeOnlyWhileRunning() + { + var headerName = "HEADER_NAME"; + _scope.SetHeader(headerName, "HEADER_VALUE"); + + var sentHeaders = new List(); + _mockMessageHandler.MockHttpResponse(request => + { + sentHeaders.Add(request.Headers.Contains(headerName)); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("RESULT") }; + }); + + var result = await _scope.PerformAsync(client => client.GetAsStringAsync("/test")); + await _client.GetAsStringAsync("/test"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result, Is.EqualTo("RESULT")); + Assert.That(sentHeaders, Is.EqualTo([true, false])); + } + } } } diff --git a/tests/Kampute.HttpClient.Test/HttpResponseExceptionTests.cs b/tests/Kampute.HttpClient.Test/HttpResponseExceptionTests.cs index c1f6b21..f1db93d 100644 --- a/tests/Kampute.HttpClient.Test/HttpResponseExceptionTests.cs +++ b/tests/Kampute.HttpClient.Test/HttpResponseExceptionTests.cs @@ -4,6 +4,7 @@ namespace Kampute.HttpClient.Test using Moq; using NUnit.Framework; using System; + using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; @@ -52,5 +53,26 @@ public async Task ExceptionFilterOnBaseStatusCode_MatchesErrorResponse() Assert.That(matched, Is.True); } + + [Test] + public void ToString_IncludesRequestResponseAndErrors() + { + using var request = new HttpRequestMessage(HttpMethod.Delete, "http://api.test.com/items/42"); + using var response = new HttpResponseMessage(HttpStatusCode.Conflict) { RequestMessage = request, ReasonPhrase = "Conflict" }; + var exception = new HttpResponseException(HttpStatusCode.Conflict, "Request failed") + { + ResponseMessage = response, + Errors = new Dictionary { ["Name"] = ["Required", "TooShort"] }, + }; + + var text = exception.ToString(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(text, Does.Contain("DELETE http://api.test.com/items/42")); + Assert.That(text, Does.Contain("409 Conflict")); + Assert.That(text, Does.Contain("Name: Required TooShort")); + } + } } } diff --git a/tests/Kampute.HttpClient.Test/HttpRestClientTests.cs b/tests/Kampute.HttpClient.Test/HttpRestClientTests.cs index 944ccde..82762fd 100644 --- a/tests/Kampute.HttpClient.Test/HttpRestClientTests.cs +++ b/tests/Kampute.HttpClient.Test/HttpRestClientTests.cs @@ -24,6 +24,7 @@ public class HttpRestClientTests { private static readonly HttpMethod TestHttpMethod = new("TEST"); + private const string BrokenMediaType = "application/x-broken"; private readonly TestContentFormatter _testContentFormatter = new(); private readonly Mock _mockMessageHandler = new(); @@ -60,6 +61,26 @@ public void DefaultConstructor_UsesSharedHttpClient() Assert.That(SharedHttpClient.ReferenceCount, Is.Zero); } + [TestCase("http://example.com/api", "users", "http://example.com/api/users")] + [TestCase("http://example.com/api/", "users", "http://example.com/api/users")] + [TestCase("http://example.com/v1/api", "users?page=2", "http://example.com/v1/api/users?page=2")] + [TestCase("http://example.com", "users", "http://example.com/users")] + public void BaseAddress_ResolvesRelativeUriUnderItsPath(string baseAddress, string relativeUri, string expectedUri) + { + _client.BaseAddress = new Uri(baseAddress); + + Assert.That(new Uri(_client.BaseAddress, relativeUri), Is.EqualTo(new Uri(expectedUri))); + } + + [Test] + public void SharedHttpClientFactory_AfterSharedClientIsCreated_CannotBeChanged() + { + using var client = new HttpRestClient(); + var factory = SharedHttpClient.Factory; + + Assert.Throws(() => SharedHttpClient.Factory = factory); + } + [Test] public async Task DefaultRequestHeaders_AreCopiedToRequestHeaders() { @@ -136,6 +157,38 @@ public async Task OnUnsupportedMediaType_ThrowsContentException() await Assert.ThrowsAsync(async () => await _client.SendAsync(TestHttpMethod, "/resource")); } + [Test] + public async Task OnUnparsableResponseBody_ThrowsContentExceptionWithParserError() + { + var parserError = new FormatException("Malformed content"); + _client.ContentFormatters.Add(MockReader(BrokenMediaType, parserError).Object); + _mockMessageHandler.MockHttpResponse(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("content", Encoding.UTF8, BrokenMediaType), + }); + + var exception = await Assert.ThrowsAsync(() => _client.SendAsync(TestHttpMethod, "/resource")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception.InnerException, Is.SameAs(parserError)); + Assert.That(exception.ObjectType, Is.EqualTo(typeof(int))); + Assert.That(exception.Content?.Headers.ContentType?.MediaType, Is.EqualTo(BrokenMediaType)); + } + } + + [Test] + public async Task OnCanceledResponseBodyRead_ThrowsCancellationUnwrapped() + { + _client.ContentFormatters.Add(MockReader(BrokenMediaType, new OperationCanceledException()).Object); + _mockMessageHandler.MockHttpResponse(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("content", Encoding.UTF8, BrokenMediaType), + }); + + await Assert.ThrowsAsync(() => _client.SendAsync(TestHttpMethod, "/resource")); + } + [Test] public async Task OnUnsuccessfulStatusCode_WithoutResponseErrorType_ThrowsStandardRestException() { @@ -170,7 +223,7 @@ public async Task OnUnsuccessfulStatusCode_ResponseMessageKeepsHeadersButContent using (Assert.EnterMultipleScope()) { Assert.That(exception.ResponseMessage.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError)); - Assert.That(exception.ResponseMessage.Headers.GetValues("X-Error-Id"), Is.EqualTo(new[] { "42" })); + Assert.That(exception.ResponseMessage.Headers.GetValues("X-Error-Id"), Is.EqualTo(["42"])); await Assert.ThrowsAsync(() => exception.ResponseMessage.Content.ReadAsStringAsync()); } } @@ -195,6 +248,22 @@ public async Task OnUnsuccessfulStatusCode_WithResponseErrorType_ThrowsCustomize } } + [Test] + public async Task OnUnsuccessfulStatusCode_WithUnreadableErrorBody_ThrowsStandardRestExceptionWithoutResponseObject() + { + using var responseContent = new StringContent("A,B", Encoding.UTF8, MediaTypeNames.Text.Csv); + _mockMessageHandler.MockHttpResponse(HttpStatusCode.BadRequest, responseContent); + + _client.ResponseErrorType = typeof(TestErrorResponse); + var exception = await Assert.ThrowsAsync(() => _client.SendAsync(TestHttpMethod, "/resource")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + Assert.That(exception.ResponseObject, Is.Null); + } + } + [Test] public async Task OnUnsuccessfulStatusCode_WithErrorHandler_RetriesRequest() { @@ -270,6 +339,67 @@ public async Task OnConnectionFailure_UsesRetryPolicy() Assert.That(attempts, Is.EqualTo(maxRetries + 1)); } + [Test] + public async Task OnResponseEndedPrematurely_UsesRetryPolicy() + { + var mockRetryPolicy = RetryTestHelpers.MockRetryPolicy(1, out var mockRetrySession); + _client.RetryPolicy = mockRetryPolicy.Object; + + var attempts = 0; + _mockMessageHandler.MockHttpResponse(request => + { + if (++attempts == 1) + throw new HttpRequestException("Error while copying content to a stream.", new HttpIOException(HttpRequestError.ResponseEnded)); + + return new HttpResponseMessage(HttpStatusCode.OK); + }); + + await _client.SendAsync(TestHttpMethod, "/test"); + + mockRetrySession.Verify(session => session.WaitToRetryAsync(It.IsAny()), Times.Once); + Assert.That(attempts, Is.EqualTo(2)); + } + + [Test] + public async Task OnNonTransientConnectionFailure_DoesNotUseRetryPolicy() + { + var mockRetryPolicy = RetryTestHelpers.MockRetryPolicy(2, out var mockRetrySession); + _client.RetryPolicy = mockRetryPolicy.Object; + + var attempts = 0; + _mockMessageHandler.MockHttpResponse(request => + { + attempts++; + throw new HttpRequestException("Connection failure", new SocketException((int)SocketError.AccessDenied)); + }); + + await Assert.ThrowsAsync(() => _client.SendAsync(TestHttpMethod, "/test")); + + mockRetrySession.Verify(session => session.WaitToRetryAsync(It.IsAny()), Times.Never); + Assert.That(attempts, Is.EqualTo(1)); + } + + [Test] + public async Task OnConnectionFailure_WithNonReusableContent_DoesNotUseRetryPolicy() + { + var mockRetryPolicy = RetryTestHelpers.MockRetryPolicy(2, out var mockRetrySession); + _client.RetryPolicy = mockRetryPolicy.Object; + + var attempts = 0; + _mockMessageHandler.MockHttpResponse(request => + { + attempts++; + throw new HttpRequestException("Connection failure", new SocketException((int)SocketError.HostUnreachable)); + }); + + using var content = new StreamContent(new TestStream(seekable: false)); + + await Assert.ThrowsAsync(() => _client.SendAsync(TestHttpMethod, "/test", content)); + + mockRetrySession.Verify(session => session.WaitToRetryAsync(It.IsAny()), Times.Never); + Assert.That(attempts, Is.EqualTo(1)); + } + [TestCase("gzip")] [TestCase("deflate")] public async Task OnConnectionFailure_WithCompressedContent_UsesRetryPolicy(string encoding) @@ -485,5 +615,13 @@ public async Task BeginHeaderScope_ModifiesRequestHeadersCorrectly() Assert.That(sent, Is.True); } + + private static Mock MockReader(string mediaType, Exception readError) + { + var reader = new Mock(); + reader.Setup(f => f.CanRead(mediaType, It.IsAny())).Returns(true); + reader.Setup(f => f.ReadAsync(It.IsAny(), It.IsAny(), It.IsAny())).ThrowsAsync(readError); + return reader; + } } } diff --git a/tests/Kampute.HttpClient.Test/SendObjectTests.cs b/tests/Kampute.HttpClient.Test/SendObjectTests.cs index 80e50a1..52ad2fc 100644 --- a/tests/Kampute.HttpClient.Test/SendObjectTests.cs +++ b/tests/Kampute.HttpClient.Test/SendObjectTests.cs @@ -115,7 +115,7 @@ public async Task SendObjectAsync_WithHttpContentPayload_SendsContentAsItIs() using (Assert.EnterMultipleScope()) { Assert.That(_sentRequests.Select(sent => sent.Request.Content), Is.EqualTo(new HttpContent[] { firstContent, secondContent })); - Assert.That(_sentRequests.Select(sent => sent.Body), Is.EqualTo(new[] { "first", "second" })); + Assert.That(_sentRequests.Select(sent => sent.Body), Is.EqualTo(["first", "second"])); } } @@ -127,7 +127,7 @@ public async Task Request_WithSendOnlyFormatter_AddsNothingToAcceptHeader() await _client.GetAsync("/resource"); - Assert.That(_sentRequests.Single().Request.Headers.Accept.Select(accept => accept.MediaType), Is.EqualTo(new[] { Constants.TestMediaType })); + Assert.That(_sentRequests.Single().Request.Headers.Accept.Select(accept => accept.MediaType), Is.EqualTo([Constants.TestMediaType])); } [Test] @@ -138,7 +138,7 @@ public async Task Request_WithReceiveOnlyFormatter_AddsItsMediaTypesToAcceptHead await _client.GetAsync("/resource"); - Assert.That(_sentRequests.Single().Request.Headers.Accept.Select(accept => accept.MediaType), Is.EqualTo(new[] { ReadOnlyMediaType, Constants.TestMediaType })); + Assert.That(_sentRequests.Single().Request.Headers.Accept.Select(accept => accept.MediaType), Is.EqualTo([ReadOnlyMediaType, Constants.TestMediaType])); } private sealed class MarkingFormatter : HttpContentFormatter diff --git a/tests/Kampute.HttpClient.Test/Utilities/ExceptionExtensionsTests.cs b/tests/Kampute.HttpClient.Test/Utilities/ExceptionExtensionsTests.cs new file mode 100644 index 0000000..a2c2f8a --- /dev/null +++ b/tests/Kampute.HttpClient.Test/Utilities/ExceptionExtensionsTests.cs @@ -0,0 +1,99 @@ +namespace Kampute.HttpClient.Test.Utilities +{ + using Kampute.HttpClient.Utilities; + using NUnit.Framework; + using System; + using System.IO; + using System.Net; + using System.Net.Http; + using System.Net.Sockets; + + [TestFixture] + public class ExceptionExtensionsTests + { + [TestCase(SocketError.AddressNotAvailable, ExpectedResult = true)] + [TestCase(SocketError.ConnectionAborted, ExpectedResult = true)] + [TestCase(SocketError.ConnectionRefused, ExpectedResult = true)] + [TestCase(SocketError.ConnectionReset, ExpectedResult = true)] + [TestCase(SocketError.HostDown, ExpectedResult = true)] + [TestCase(SocketError.HostNotFound, ExpectedResult = true)] + [TestCase(SocketError.HostUnreachable, ExpectedResult = true)] + [TestCase(SocketError.Interrupted, ExpectedResult = true)] + [TestCase(SocketError.NetworkDown, ExpectedResult = true)] + [TestCase(SocketError.NetworkReset, ExpectedResult = true)] + [TestCase(SocketError.NetworkUnreachable, ExpectedResult = true)] + [TestCase(SocketError.NoBufferSpaceAvailable, ExpectedResult = true)] + [TestCase(SocketError.NotConnected, ExpectedResult = true)] + [TestCase(SocketError.OperationAborted, ExpectedResult = true)] + [TestCase(SocketError.Shutdown, ExpectedResult = true)] + [TestCase(SocketError.SocketError, ExpectedResult = true)] + [TestCase(SocketError.TimedOut, ExpectedResult = true)] + [TestCase(SocketError.TooManyOpenSockets, ExpectedResult = true)] + [TestCase(SocketError.TryAgain, ExpectedResult = true)] + [TestCase(SocketError.AccessDenied, ExpectedResult = false)] + [TestCase(SocketError.AddressAlreadyInUse, ExpectedResult = false)] + [TestCase(SocketError.MessageSize, ExpectedResult = false)] + [TestCase(SocketError.NoData, ExpectedResult = false)] + [TestCase(SocketError.NoRecovery, ExpectedResult = false)] + public bool IsTransientNetworkError_ForSocketError_ClassifiesByErrorCode(SocketError socketError) + { + var error = new HttpRequestException("Connection failure", new SocketException((int)socketError)); + + return error.IsTransientNetworkError(); + } + + [TestCase(WebExceptionStatus.ConnectFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.ConnectionClosed, ExpectedResult = true)] + [TestCase(WebExceptionStatus.KeepAliveFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.NameResolutionFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.PipelineFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.ProxyNameResolutionFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.ReceiveFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.SendFailure, ExpectedResult = true)] + [TestCase(WebExceptionStatus.Timeout, ExpectedResult = true)] + [TestCase(WebExceptionStatus.ProtocolError, ExpectedResult = false)] + [TestCase(WebExceptionStatus.SecureChannelFailure, ExpectedResult = false)] + [TestCase(WebExceptionStatus.ServerProtocolViolation, ExpectedResult = false)] + [TestCase(WebExceptionStatus.TrustFailure, ExpectedResult = false)] + public bool IsTransientNetworkError_ForWebExceptionStatus_ClassifiesByStatus(WebExceptionStatus status) + { + var error = new HttpRequestException("Request failure", new WebException("Request failure", status)); + + return error.IsTransientNetworkError(); + } + + [Test] + public void IsTransientNetworkError_ForResponseEndedPrematurely_ReturnsTrue() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(new HttpRequestException("Request failure", new IOException("The response ended prematurely.")).IsTransientNetworkError(), Is.True); + Assert.That(new HttpRequestException("Request failure", new HttpIOException(HttpRequestError.ResponseEnded)).IsTransientNetworkError(), Is.True); + } + } + + [Test] + public void IsTransientNetworkError_ForHttpProtocolError_ReturnsFalse() + { + var error = new HttpRequestException("Request failure", new HttpProtocolException(0x1, "PROTOCOL_ERROR", null)); + + Assert.That(error.IsTransientNetworkError(), Is.False); + } + + [Test] + public void IsTransientNetworkError_ForTimeout_ReturnsTrue() + { + var error = new HttpRequestException("Connection failure", new TimeoutException()); + + Assert.That(error.IsTransientNetworkError(), Is.True); + } + + [Test] + public void IsTransientNetworkError_WithoutNetworkCause_ReturnsFalse() + { + var error = new HttpRequestException("Invalid response", new InvalidOperationException()); + + Assert.That(error.IsTransientNetworkError(), Is.False); + } + } +} diff --git a/tests/Kampute.HttpClient.Test/Xml/HttpRestClientXmlExtensionsTests.cs b/tests/Kampute.HttpClient.Test/Xml/HttpRestClientXmlExtensionsTests.cs index 088be8c..ad7c43f 100644 --- a/tests/Kampute.HttpClient.Test/Xml/HttpRestClientXmlExtensionsTests.cs +++ b/tests/Kampute.HttpClient.Test/Xml/HttpRestClientXmlExtensionsTests.cs @@ -77,7 +77,7 @@ public async Task UseXml_AdvertisesXmlInAcceptHeader() using (Assert.EnterMultipleScope()) { - Assert.That(accepted, Is.EqualTo($"{MediaTypeNames.Application.Xml}, {MediaTypeNames.Text.Xml}, {MediaTypeNames.Application.ProblemXml}")); + Assert.That(accepted, Is.EqualTo($"{MediaTypeNames.Application.Xml}, {MediaTypeNames.Text.Xml}")); Assert.That(result, Is.EqualTo(new PlainModel { Name = "Test" })); } } diff --git a/tests/Kampute.HttpClient.Test/Xml/XmlFormatterTests.cs b/tests/Kampute.HttpClient.Test/Xml/XmlFormatterTests.cs index 0a3b1d9..e361d4b 100644 --- a/tests/Kampute.HttpClient.Test/Xml/XmlFormatterTests.cs +++ b/tests/Kampute.HttpClient.Test/Xml/XmlFormatterTests.cs @@ -4,6 +4,7 @@ namespace Kampute.HttpClient.Test.Xml using NUnit.Framework; using System; using System.Net.Http; + using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; @@ -25,8 +26,8 @@ public void MediaTypes_ReadXmlTextXmlAndProblemXml_WriteXml() using (Assert.EnterMultipleScope()) { - Assert.That(formatter.GetReadableMediaTypes(typeof(PlainModel)), Is.EqualTo(new[] { MediaTypeNames.Application.Xml, MediaTypeNames.Text.Xml, MediaTypeNames.Application.ProblemXml })); - Assert.That(formatter.GetWritableMediaTypes(typeof(PlainModel)), Is.EqualTo(new[] { MediaTypeNames.Application.Xml })); + Assert.That(formatter.GetReadableMediaTypes(typeof(PlainModel)), Is.EqualTo([MediaTypeNames.Application.Xml, MediaTypeNames.Text.Xml])); + Assert.That(formatter.GetWritableMediaTypes(typeof(PlainModel)), Is.EqualTo([MediaTypeNames.Application.Xml])); Assert.That(formatter.CanRead(MediaTypeNames.Application.Xml, typeof(ContractModel)), Is.True); Assert.That(formatter.CanRead("Application/XML", typeof(PlainModel)), Is.True); Assert.That(formatter.CanRead(MediaTypeNames.Text.Xml, typeof(PlainModel)), Is.True); @@ -55,6 +56,36 @@ public async Task ReadAsync_WithXmlSerializer_ReadsObject(string encodingName) Assert.That(result, Is.EqualTo(expected)); } + [Test] + public async Task ReadAsync_WithoutCharsetOrByteOrderMark_DecodesWithXmlEncodingDeclaration() + { + var body = Encoding.Latin1.GetBytes(PlainModelXml("iso-8859-1", "Café")); + + var result = await ReadBytes(body, charset: null); + + Assert.That(result, Is.EqualTo(new PlainModel { Name = "Café" })); + } + + [Test] + public async Task ReadAsync_WithCharsetAndNoByteOrderMark_DecodesWithCharsetOverEncodingDeclaration() + { + var body = Encoding.Latin1.GetBytes(PlainModelXml("utf-8", "Café")); + + var result = await ReadBytes(body, charset: "iso-8859-1"); + + Assert.That(result, Is.EqualTo(new PlainModel { Name = "Café" })); + } + + [Test] + public async Task ReadAsync_WithByteOrderMark_DecodesWithByteOrderMarkOverCharset() + { + byte[] body = [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes(PlainModelXml("utf-8", "Café"))]; + + var result = await ReadBytes(body, charset: "iso-8859-1"); + + Assert.That(result, Is.EqualTo(new PlainModel { Name = "Café" })); + } + [TestCase("utf-8")] [TestCase("utf-16BE")] public async Task ReadAsync_WithDataContractSerializer_ReadsObject(string encodingName) @@ -173,6 +204,18 @@ public void Write_WithUnsupportedMediaType_ThrowsNotSupportedException() return await formatter.ReadAsync(content, modelType); } + private static string PlainModelXml(string declaredEncoding, string name) + { + return $"<{nameof(PlainModel)}>{name}"; + } + + private static async Task ReadBytes(byte[] body, string? charset) + { + using var content = new ByteArrayContent(body); + content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Xml) { CharSet = charset }; + return await new XmlFormatter { Serializer = XmlSerializerKind.XmlSerializer }.ReadAsync(content, typeof(PlainModel)); + } + private static async Task Write(XmlFormatter formatter, object payload) { using var content = formatter.Write(payload, MediaTypeNames.Application.Xml);