Xpandables.Rests
11.0.1
dotnet add package Xpandables.Rests --version 11.0.1
NuGet\Install-Package Xpandables.Rests -Version 11.0.1
<PackageReference Include="Xpandables.Rests" Version="11.0.1" />
<PackageVersion Include="Xpandables.Rests" Version="11.0.1" />
<PackageReference Include="Xpandables.Rests" />
paket add Xpandables.Rests --version 11.0.1
#r "nuget: Xpandables.Rests, 11.0.1"
#:package Xpandables.Rests@11.0.1
#addin nuget:?package=Xpandables.Rests&version=11.0.1
#tool nuget:?package=Xpandables.Rests&version=11.0.1
π¦ System.Rests
Declarative, type-safe REST client with attribute-based routing, composable request/response pipelines, and resilience policies
Getting Started β’ Defining Requests β’ Fluent Builder β’ Sending Requests β’ Response Handling β’ Pipelines β’ Interceptors β’ Authentication β’ JSON Patch β’ Streaming β’ Resilience β’ Logging β’ DI Registration β’ Native AOT
π Overview
Xpandables.Rests is an AOT-compatible REST client built on System.Net.Http and Microsoft.Extensions.Http.
An API call is a type: a record or class carrying a [RestGet], [RestPost], β¦ attribute and implementing the
interfaces that provide its values (path, query string, headers, cookies, body). The client builds the
HttpRequestMessage through an ordered pipeline of request composers, sends it, and turns the
HttpResponseMessage into a RestResponse (carrying a Result from System.Results) through response composers.
- Attribute-based requests, completed at compile time by the
RestRequestGeneratorof Xpandables.Generators β nothing is read by reflection. - A fluent
RestRequestBuilderfor requests built in code, immutable and safe to share. - JSON bodies and results through your source-generated
JsonSerializerContext(IJsonSerializerContext). - JSON Patch (RFC 6902), byte array, stream, form URL-encoded and multipart bodies.
- Streamed (
IAsyncEnumerable<T>) and paged (IAsyncPagedEnumerable<T>) responses. - Request and response interceptors; token providers for secured requests; correlation headers on every request.
- Retry (idempotent methods only,
Retry-Afterhonoured), circuit breaker, and a per-attempt timeout for retried methods. - Failures as results with meaningful statuses; configuration errors as
RestConfigurationException.
π Getting Started
dotnet add package Xpandables.Rests
The package brings the RestRequestGenerator (Xpandables.Generators) as an analyzer. A minimal setup:
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.DependencyInjection;
// 1. JSON metadata for every body, result and streamed element type (Native AOT: no reflection).
[JsonSerializable(typeof(CreateUserRequest))]
[JsonSerializable(typeof(User))]
[JsonSerializable(typeof(User[]))]
internal sealed partial class AppJsonContext : JsonSerializerContext;
builder.Services.AddSingleton(new JsonSerializerOptions
{
TypeInfoResolverChain = { AppJsonContext.Default }
});
builder.Services.AddXJsonSerializerContext(); // IJsonSerializerContext (Xpandables.Net)
// 2. The composers, then the client (the attribute provider and the factories are added with it).
builder.Services
.AddXRestRequestComposers()
.AddXRestResponseComposers()
.AddXRestClient((_, client) => client.BaseAddress = new Uri("https://api.example.com"));
// 3. Send.
public sealed class UsersService(IRestClient client)
{
public async Task<User?> CreateAsync(string name, string email, CancellationToken cancellationToken)
{
using RestResponse<User> response = (await client.SendAsync(
new CreateUserRequest(name, email), cancellationToken)).ToRestResponse<User>();
return response.Result.IsSuccess ? response.Result.Value : null;
}
}
π Defining Requests
A request implements IRestRequest (or one of its result interfaces), carries one [Restβ¦] attribute, and is declared
partial (with every type containing it) so that the generator can complete it. It implements the interface of each
value it sends:
using System.Net.Http.Headers;
using System.Rests;
// POST with a JSON body: IRestString sends the request itself by default
[RestPost("/api/users")]
public sealed partial record CreateUserRequest(string Name, string Email)
: IRestRequestResult<User>, IRestString;
// GET with a query string (Location = Query is the default of [RestGet])
[RestGet("/api/users")]
public sealed partial record GetUsersRequest(int? Page = null, int? PageSize = null)
: IRestRequestResult<User[]>, IRestQueryString
{
public IDictionary<string, string?>? GetQueryString() => new Dictionary<string, string?>
{
["page"] = Page?.ToString(), // a null value is omitted from the URL
["pageSize"] = PageSize?.ToString()
};
}
// GET with a path parameter
[RestGet("/api/users/{userId}", Location = RestSettings.Location.Path)]
public sealed partial record GetUserRequest(Guid UserId)
: IRestRequestResult<User>, IRestPathString
{
public IDictionary<string, string> GetPathString() =>
new Dictionary<string, string> { ["userId"] = UserId.ToString() };
}
// DELETE without a result
[RestDelete("/api/users/{userId}", Location = RestSettings.Location.Path)]
public sealed partial record DeleteUserRequest(Guid UserId) : IRestRequest, IRestPathString
{
public IDictionary<string, string> GetPathString() =>
new Dictionary<string, string> { ["userId"] = UserId.ToString() };
}
// Basic authentication
[RestGet("/api/admin/users", Location = RestSettings.Location.BasicAuth)]
public sealed partial record GetAdminUsersRequest(string Credentials)
: IRestRequestResult<User[]>, IRestBasicAuthentication
{
public AuthenticationHeaderValue GetAuthenticationHeaderValue() => new("Basic", Credentials);
}
// No parameters and no body: sent as is
[RestGet("/health")]
public sealed partial record Ping : IRestRequest;
Result interfaces
| Interface | Response value |
|---|---|
IRestRequest |
None, the body as text, or a Stream for a binary body (see Response Handling) |
IRestRequestResult<TResult> |
TResult, deserialized from the JSON body |
IRestRequestStream<TResult> |
IAsyncEnumerable<TResult?>, read as the body arrives |
IRestRequestStreamPaged<TResult> |
IAsyncPagedEnumerable<TResult?> with its Pagination |
IRestRequest.Name (the type name by default) names the request in the logs; ResultType is set by the result
interfaces. A public string Name property of the request β the Name parameter of a positional record such as
CreateUserRequest above β implements IRestRequest.Name, so its value is what the logs show: name such a property
otherwise when it holds personal data.
Attributes
All attributes derive from RestAttribute, take the path in their constructor, and accept these init properties:
| Property | Default | Meaning |
|---|---|---|
Path |
"/" |
Relative or absolute URI, with {key} placeholders for IRestPathString |
Method |
POST |
RestSettings.Method (set by each attribute) |
Location |
Body |
RestSettings.Location flags: Body, Query, Path, Header, Cookie, BasicAuth |
BodyFormat |
String |
RestSettings.BodyFormat: String, ByteArray, Multipart, Stream, FormUrlEncoded |
ContentEncoding |
None |
RestSettings.ContentEncoding: None, GZip, Brotli, Zstandard β compresses the body (.NET 11, see below) |
ContentType |
application/json |
Content type of the body; parameters are accepted (application/json; charset=utf-8) |
Accept |
application/json |
Accept header; a list with qualities is accepted (application/json, text/plain;q=0.5) |
IsSecured |
false |
Marks the request for authorization (see Authentication) |
Scheme |
"Bearer" |
Scheme of the Authorization header of a secured request |
| Attribute | Method | Differs from the defaults |
|---|---|---|
[RestPost] |
POST | IsSecured = true |
[RestGet] |
GET | Location = Query |
[RestPut] |
PUT | IsSecured = true |
[RestDelete] |
DELETE | IsSecured = true |
[RestPatch] |
PATCH | IsSecured = true, ContentType = application/json-patch+json |
[RestHead] |
HEAD | |
[RestOptions] |
OPTIONS | |
[RestTrace] |
TRACE | |
[RestConnect] |
CONNECT |
RestAttribute is immutable. Media types come from System.Net.Mime.MediaTypeNames; RestSettings.ContentType adds
Apng and the JsonHeader / XmlHeader accept lists.
Compressed request bodies
ContentEncoding sends the composed body compressed (the .NET 11 GZipCompressedContent, BrotliCompressedContent or
ZstandardCompressedContent, fastest level) with Content-Encoding: gzip, br or zstd; the content type is kept:
[RestPost("/imports", ContentEncoding = RestSettings.ContentEncoding.Zstandard)]
public sealed partial class ImportRowsRequest(IReadOnlyList<Row> rows) : IRestString
{
public object GetStringContent() => rows;
}
- The server must accept the encoding: ASP.NET Core does with
app.UseRequestDecompression()(gzip, br and, from .NET 11, zstd). Set it per request, for the endpoints known to accept it. - A compressed body is sent again by a retry when its uncompressed body can be (a string, byte array or seekable stream body), and the request body log shows it uncompressed.
Value interfaces
| Interface | Member | Location / BodyFormat | Sent as |
|---|---|---|---|
IRestPathString |
IDictionary<string, string> GetPathString() |
Path |
Each {key} of the path (case-insensitive) replaced by its percent-encoded value; a null, empty, . or .. value throws ArgumentException (it would join or remove a segment) |
IRestQueryString |
IDictionary<string, string?>? GetQueryString() |
Query |
Appended to the path (after an existing query, before a fragment), URL-encoded; null values omitted |
IRestHeader |
IReadOnlyCollection<ElementEntry> GetHeaders(), string? GetHeaderModelName() |
Header |
Request headers (see below) |
IRestCookie |
IDictionary<string, object?> GetCookieHeaderValue() |
Cookie |
One Cookie header, name=value; β¦, values percent-encoded (invariant culture), blank names skipped |
IRestBasicAuthentication |
AuthenticationHeaderValue GetAuthenticationHeaderValue() |
BasicAuth |
The Authorization header (any scheme) |
IRestString |
object GetStringContent() (the request itself by default) |
Body + String |
JSON, UTF-8 bytes with Content-Length; charset=utf-8 added to the content type when absent |
IRestPatch |
Collection<IPatchOperation> PatchOperations |
Body + String |
A JSON Patch document (see JSON Patch), UTF-8; charset=utf-8 added to the content type when absent |
IRestByteArray |
ByteArrayContent GetByteArrayContent() |
Body + ByteArray |
The content as given |
IRestStream |
Stream GetStream() |
Body + Stream |
A StreamContent around the stream, disposed with the request |
IRestFormUrlEncoded |
FormUrlEncodedContent GetFormUrlEncodedContent() |
Body + FormUrlEncoded |
The content as given |
IRestMultipart |
MultipartFormDataContent GetMultipartContent() |
Body + Multipart |
The content as given |
- Headers replace any value already set under the same name. A content header (
Content-Language,Content-Dispositionβ¦) goes to the body's headers, and is ignored when there is no body. WhenGetHeaderModelName()returns a name, the entries are added as a single header of that name:key1,value1;key2,value2. - JSON bodies are serialized with the metadata of their runtime type from
IJsonSerializerContext; a type without metadata (an anonymous type, for example) throwsRestConfigurationExceptionon the first send. - A body without a content type takes the attribute's
ContentType. - The message owns the
HttpContentthe request returns: it is disposed with the message, so return a new instance on each call.
Location rules
The attribute's Location (and, for a body, its BodyFormat) must agree with the interfaces the request implements,
checked before anything is composed:
- every value interface needs its flag (
IRestPathStringβPath,IRestQueryStringβQuery,IRestHeaderβHeader,IRestCookieβCookie,IRestBasicAuthenticationβBasicAuth, a body interface βBodywith aBodyFormatit serves); Path,Header,CookieandBasicAuthneed their interface.QueryandBodyare the defaults of the attributes, so a request without parameters or without a body may carry them;- a request implements at most one body interface (
IRestString,IRestPatch,IRestByteArray,IRestMultipart,IRestStream,IRestFormUrlEncoded): a request has one body.
A disagreement throws RestConfigurationException rather than sending a request without its body, or with one body
in place of another. Requests built with RestRequestBuilder compute their location and are not checked. Whatever
the request, a path that still holds a {placeholder} once composed throws InvalidOperationException before anything
is sent.
π§± Building Requests with RestRequestBuilder
RestRequestBuilder builds requests in code, without a type or an attribute. Build() returns an immutable request
definition: keep it in a static readonly field and send it concurrently; later changes to the builder never alter it.
using System.Collections;
using System.Net.Http.Headers;
using System.Rests;
using Microsoft.Extensions.DependencyInjection;
// A typed result
static readonly IRestRequestResult<User> GetUser = RestRequestBuilder.Create<User>()
.Get("/api/users/{id}")
.WithPathParameter("id", "42")
.WithQueryParameter("include", "roles")
.Build();
// A JSON body
IRestRequest create = RestRequestBuilder.Create()
.Post("/api/users")
.WithBody(new CreateUser("Jane", "jane@example.com"))
.Build();
// Values computed for each send, from the caller's services
static readonly IRestRequestStream<Event> Events = RestRequestBuilder.CreateStream<Event>()
.Get(sp => $"/api/tenants/{sp.GetRequiredService<ITenant>().Id}/events")
.RequiresAuthentication(sp => new AuthenticationHeaderValue("Bearer", sp.GetRequiredService<ITokenStore>().Token))
.WithHeaders(sp => ElementCollection.With("X-Request-Source", "worker"))
.Build();
| Entry point | Builds |
|---|---|
RestRequestBuilder.Create() |
IRestRequest |
RestRequestBuilder.Create<TResult>() |
IRestRequestResult<TResult> |
RestRequestBuilder.CreateStream<TResult>() |
IRestRequestStream<TResult> |
RestRequestBuilder.CreateStreamPaged<TResult>() |
IRestRequestStreamPaged<TResult> |
| Method | Effect |
|---|---|
Get / Post / Put / Delete / Patch / Head / Options / Trace / Connect (path) or (Func<IServiceProvider, string>) |
Method and path (or a path computed for each send) |
WithPathParameter(key, value) / WithPathParameters(dictionary) |
{key} placeholders |
WithQueryParameter(key, value) / WithQueryParameters(dictionary) |
Query string (null values omitted) |
WithHeaders(ElementCollection, modelName?) / WithHeaders(Func<IServiceProvider, ElementCollection>, modelName?) |
Headers |
WithCookie(key, value) |
A cookie |
WithBody(body) |
JSON body (IRestString) |
WithContentType(contentType) / WithAccept(accept) |
Content-Type / Accept (both application/json by default) |
RequiresAuthentication(AuthenticationHeaderValue) / (Func<IServiceProvider, AuthenticationHeaderValue>) / (scheme, parameter) |
Authorization header; marks the request secured |
RequiresAuthorization() |
Marks the request secured, the header being supplied at send time (see Authentication) |
WithScheme(scheme) |
Scheme of a secured request (Bearer by default) |
Build() throws InvalidOperationException when the method or the path is missing. The last call wins: a parameter,
query parameter or cookie set again replaces the earlier value, and a path, authentication header or headers replace
the factory set for them earlier (and the other way round).
The location is computed from what the request carries (Query for GET, DELETE, HEAD, OPTIONS and TRACE). Each
factory runs once per send against the services of the caller, so a per-user token or a per-tenant path never leaks
between concurrent sends. RequiresAuthentication sets the Authorization header, sent as given;
RequiresAuthorization() leaves it to the client's token provider (see
Authentication).
π¨ Sending Requests
IRestClient client = ...; // injected
using RestResponse<User> response = (await client.SendAsync(
new CreateUserRequest("John", "john@example.com"), cancellationToken)).ToRestResponse<User>();
if (response.Result.IsSuccess)
{
User user = response.Result.Value!;
}
else
{
Console.WriteLine($"{(int)response.Result.StatusCode}: {response.Result.Exception?.Message}");
}
A failure body is buffered and read once, as bytes, and stays readable for later response interceptors; problem details
are parsed from UTF-8 without decoding the body whole, other text is decoded once, a non-UTF-8 Content-Type charset is
honoured, and the exception message carries an excerpt of at most Logging.MaxLoggedBodyLength characters, then
β¦[truncated].
SendAsync never throws for an HTTP outcome. Always dispose the response (using): it may own the HTTP response and
its connection. IRestClient.HttpClient exposes the underlying client, owned by IHttpClientFactory: do not dispose it.
The message is sent with the HttpClient's DefaultRequestVersion and DefaultVersionPolicy.
Outcomes
| What happened | Result of SendAsync |
|---|---|
A 2xx with a body |
Success with the value (see Response Handling) |
204 No Content, or an empty body |
Success without a value (GetObjectValue() is null) |
A 2xx whose body is not the declared result (IRestRequestResult<T>) |
Failure, 502 Bad Gateway, with the JsonException |
| The server answered with an error status | Failure with that status; the body becomes the failure result (problem details are read) and the HttpRequestException message carries at most Logging.MaxLoggedBodyLength characters of it |
| A request interceptor returned a response | That response; nothing is sent |
The client timeout (RestClientOptions.Timeout), the HttpClient.Timeout (100 s by default) or a handler's ConnectTimeout, whichever elapsed first |
Failure, 408 Request Timeout, with a TimeoutException naming that timeout |
| The server could not be reached (DNS, connection, TLS, proxy) | Failure, 503 Service Unavailable, with the HttpRequestException |
| The exchange failed after the server was reached | Failure, 502 Bad Gateway, with the HttpRequestException |
| A per-attempt timeout of the resilience pipeline / an open circuit | Failure, 504 / 503 |
With a retry policy, a retryable status (a 429 or 503, for example) whose Retry-After reaches past the client's Timeout |
That failure at once, its Retry-After in Result.Headers; not retried |
| Any other exception during the exchange | Failure carrying the exception, with the status it maps to |
| The caller's token was cancelled | Throws OperationCanceledException |
A read of a streamed or binary success body waits longer than ReadIdleTimeout (30 s) for data |
That read throws TimeoutException |
An ArgumentException or InvalidOperationException raised while the request is composed (a null, empty, . or .. path value, a placeholder left in the path, a failing attribute builder, composer or request interceptor) |
Throws it; nothing is sent |
A misconfiguration (no JSON metadata or JSON serializer context, a composer or interceptor the container cannot build, a Location that disagrees with the request, several body interfaces, an invalid path, Accept or content type, no composer for its values, no response composer for the response, no IRestAttributeBuilder, no stream deserializer) |
Throws RestConfigurationException |
A failure raised by the client because the exchange did not complete (a timeout, a transport or pipeline
exception) carries the exception that caused it (Result.Exception) and no headers; a failure returned by the server
carries an HttpRequestException whose StatusCode is that status, and the forwarded response headers.
A failure result never copies the client's request headers (they typically hold the Authorization header).
π Response Handling
RestResponse response = await client.SendAsync(request);
// The outcome is the Result
bool ok = response.Result.IsSuccess;
HttpStatusCode status = response.Result.StatusCode;
ElementCollection headers = response.Result.Headers; // Location, Retry-After, ETag, β¦ (see below)
HttpResponseHeaders? all = response.Headers; // every response header received
Exception? error = response.Result.Exception;
object? value = response.Result.GetObjectValue();
Version version = response.Version;
string? reason = response.ReasonPhrase;
// Typed access
RestResponse<User> typed = response.ToRestResponse<User>();
User? user = typed.Result.Value;
// Typed access that checks the value's type first (InvalidOperationException on a mismatch)
RestResponse<User> checkedResponse = response.ToRestResponseValidated<User>();
// Back to the non-generic form
RestResponse nonGeneric = typed.ToRestResponse();
A conversion (ToRestResponse, ToRestResponse<T>, ToRestResponseValidated<T>, or the implicit conversions between
RestResponse and RestResponse<T>) hands over what the response owns β its result value and, for a streaming or
binary response, the HTTP response behind it β to the converted response, keeping headers and extensions. Dispose the
converted response. A value that ToRestResponse<T> does not carry over (it is not a T; the converted result holds
default) stays with the original, which disposes it when disposed.
Result.Headers receives the headers a caller acts on β Location, Retry-After, ETag, Last-Modified,
Content-Language, Content-Disposition, WWW-Authenticate, Link β and those named in
RestClientOptions.ForwardedResponseHeaders: a result's headers can be written to the application's own HTTP response,
and upstream headers (Set-Cookie, internal routing headers) must not travel that far. The response headers, not the
content headers, stay on RestResponse.Headers.
The response composer is chosen by the response and the request:
| Composer | Composes | Value |
|---|---|---|
RestResponseFailureComposer |
A non-success status | Failure result read from the body |
RestResponseNoContentComposer |
A success with 204 or a body of length zero |
None |
RestResponseContentComposer |
A success with a body, request without result type | A Stream for a binary body (application/octet-stream, image/*, audio/*, video/*, PDF, archives, Office documents); otherwise the body as a string (none when empty) |
RestResponseResultComposer |
A success with a body, IRestRequestResult<T> |
T, deserialized from the body bytes, transcoded first when the Content-Type charset is not UTF-8; an unknown or unregistered charset is read as UTF-8 (502 when unreadable) |
RestResponseStreamComposer |
A success with a body, IRestRequestStream<T> |
IAsyncEnumerable<T?>; an unknown charset fails when enumerated |
RestResponseStreamPagedComposer |
A success with a body, IRestRequestStreamPaged<T> |
IAsyncPagedEnumerable<T?>; an unknown charset fails when enumerated |
Every response is read with HttpCompletionOption.ResponseHeadersRead. A text, JSON or error body, which its composer
reads whole, is buffered once within HttpClient.MaxResponseContentBufferSize. A binary body is returned as a Stream
read from the network, readable until the response is disposed; a streamed or paged body is read as it is enumerated.
Each read of either waits at most ReadIdleTimeout for data, then throws TimeoutException.
π§ Request Composer Pipeline
RestRequestFactory builds the message: it sets the method, URI and Accept header from the attribute, runs every
request composer whose CanCompose accepts the request, in ascending Order (registration order among equals),
completes the message (content type, authorization flag), and runs the request interceptors last.
Each composer is asked just before it would run, so it sees what the earlier ones wrote.
| Composer | Order | Handles |
|---|---|---|
RestPathStringComposer |
10 | {key} replacement in the URL path |
RestQueryStringComposer |
20 | Query string, appended to the path built so far |
RestCookieComposer |
40 | Cookie header |
RestBasicAuthComposer |
50 | Authorization header |
RestStringComposer |
100 | JSON body |
RestPatchComposer |
100 | JSON Patch body |
RestByteArrayComposer |
100 | Byte array body |
RestStreamComposer |
100 | Stream body |
RestFormUrlEncodedComposer |
100 | Form URL-encoded body |
RestMultipartComposer |
100 | Multipart form data |
RestHeaderComposer |
110 | Custom headers; a content header goes to the body, which exists by then |
RestMultipartComposer sets the body, replacing any content already set; the other body composers add their content as
a part when the message already carries a MultipartFormDataContent (set by a custom composer that runs earlier), and
set the body otherwise. A request that has values to send but that no composer handles throws
RestConfigurationException (register the composers with AddXRestRequestComposers()). If an interceptor or a composer fails, the message and any content already
attached to it are disposed.
Custom composers
public sealed class ApiVersionComposer : IRestRequestComposer
{
public int Order => 120; // after the headers
public bool CanCompose(RestRequestContext context) => true;
public ValueTask ComposeAsync(RestRequestContext context, CancellationToken cancellationToken = default)
{
context.Message.Headers.TryAddWithoutValidation("X-Api-Version", "2");
return ValueTask.CompletedTask;
}
}
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IRestRequestComposer, ApiVersionComposer>());
RestRequestContext carries the Attribute, the Request, the Message being built, the sending client's Options
and the caller's Services. An IRestResponseComposer has CanCompose(RestResponseContext) and ComposeAsync; the
first registered response composer whose CanCompose accepts the response composes it, so a custom one registered
before AddXRestResponseComposers() takes precedence. When no response composer accepts the response,
RestConfigurationException is thrown.
RestUriExtensions.AddPathString(path, values) and AddQueryString(path, values) are the helpers the composers use,
available to custom ones.
πͺ Interceptors
public sealed class TenantInterceptor(ITenant tenant) : IRestRequestInterceptor
{
public int Order => 0;
public ValueTask<RestResponse?> InterceptAsync(RestRequestContext context, CancellationToken cancellationToken = default)
{
context.Message.Headers.TryAddWithoutValidation("X-Tenant", tenant.Id);
return default; // null: send the request
}
}
public sealed class AuditInterceptor : IRestResponseInterceptor
{
public ValueTask<RestResponse> InterceptAsync(
RestResponseContext context, RestResponse response, CancellationToken cancellationToken = default)
=> ValueTask.FromResult(response); // inspect, or return another response
}
builder.Services.AddXRestRequestInterceptor<TenantInterceptor>();
builder.Services.AddXRestResponseInterceptor<AuditInterceptor>();
- Request interceptors run after the composers, in ascending
Order(registration order among equals): they see the message as it is sent (final URI, headers, content, the authorization flag) and write into it; the message itself is never replaced (RestRequestContext.Messageis init-only). Returning aRestResponseshort-circuits the send: no later interceptor runs, nothing is sent, andSendAsyncreturns that response. - Response interceptors run after the response composer, in ascending
Order; each receives the response the previous one returned. They run for every response received from the server, not for a response a request interceptor returned nor for a failure the client raises itself (a timeout, a transport exception). - Interceptors are registered as transient and resolved for each request from the caller's services.
AddXRestAcceptLanguage() registers RestAcceptLanguageInterceptor, which sends CultureInfo.CurrentUICulture as the
Accept-Language header of every request that does not set one (none for the invariant culture). No Accept-Language
is sent otherwise.
Correlation
Every client registered by AddXRestClient* sends the caller's correlation context: X-Correlation-Id and
X-Causation-Id, each when the context holds it as printable ASCII (no whitespace or control character) and the request
does not carry the header already. The context is read from the registered ICorrelationContextAccessor, or from the
ambient scope (AsyncLocalCorrelationContextAccessor) when none is registered. The W3C trace context (traceparent) is
propagated by HttpClient itself.
π Authentication and Authorization
- A header carried by the request: implement
IRestBasicAuthenticationwithLocation.BasicAuth, or useRequiresAuthentication(...)on the builder. The header is sent as given, whatever its scheme. - A secured request (
IsSecured = true, the default of[RestPost],[RestPut],[RestDelete]and[RestPatch], orRequiresAuthorization()on the builder): when it carries noAuthorizationheader of its own it is flagged in itsOptions, and the client's token provider writes the header.
public sealed class ApiTokenProvider(ITokenClient tokens) : IRestTokenProvider
{
public async ValueTask<RestToken> GetTokenAsync(RestTokenContext context, CancellationToken cancellationToken)
{
AccessToken token = await tokens.RequestAsync(forceRefresh: context.ForceRefresh, cancellationToken);
return new RestToken(context.Scheme, token.Value, token.ExpiresOn);
}
}
builder.Services
.AddXRestClientWithResilience("payments", (_, client) => client.BaseAddress = new Uri("https://api.example.com"))
.AddXRestTokenProvider<ApiTokenProvider>();
AddXRestTokenProvider<TProvider>() registers the provider for that client only, as a singleton keyed by the client's
name: it is called from the client's message handler, outside the caller's scope. The client keeps the token until 30
seconds before its ExpiresOn (a token without one is kept until the server rejects it) and asks the provider for one
token at a time. A token that expires within 30 seconds, or has already expired, is not kept: a provider that returns
one is asked on every request. When the server answers 401 to a secured request, the client drops the token. When
the body can be sent again (see Resilience), it asks for a new token
(RestTokenContext.ForceRefresh) and sends the request once more; a second 401 is returned. A body that cannot be
sent again gets the 401, and the next request asks for a new token. Call it after AddXRestClientWithResilience:
each attempt then carries the current token.
A message that carries an Authorization header when it is sent keeps it: one set by an interceptor, or the client's
HttpClient.DefaultRequestHeaders.Authorization. Without a token provider, a secured request goes out without a header
of its own, so the client's default header applies. RestToken.ToString() never shows the token's value.
π JSON Patch (RFC 6902)
using System.Collections.ObjectModel;
using System.Rests;
using static System.Rests.RestSettings;
// The operations are a property
[RestPatch("/api/users/{userId}", Location = RestSettings.Location.Path | RestSettings.Location.Body)]
public sealed partial class PatchUserRequest(Guid userId) : IRestPatch, IRestRequestResult<User>, IRestPathString
{
public Collection<IPatchOperation> PatchOperations { get; } =
[
Patch.Replace("/name", "Jane"),
Patch.Test("/version", 2),
Patch.Add("/roles", new[] { "admin" }),
Patch.Remove("/email"),
];
public IDictionary<string, string> GetPathString() => new Dictionary<string, string> { ["userId"] = userId.ToString() };
}
// Or derive from RestContentPatch<T>, which builds them from the record
[RestPatch("/api/users/{userId}", Location = RestSettings.Location.Path | RestSettings.Location.Body)]
public sealed partial record RenameUser(Guid UserId, string Name) : RestContentPatch<RenameUser>, IRestPathString
{
public IDictionary<string, string> GetPathString() => new Dictionary<string, string> { ["userId"] = UserId.ToString() };
}
var rename = new RenameUser(userId, "Jane") { PatchOperationsBuilder = r => [Patch.Replace("/name", r.Name)] };
The body is a JSON array sent with the attribute's ContentType: application/json-patch+json for [RestPatch]. Each
operation is written with op, from (when set), path and value (always for add, replace and test, null
included, as RFC 6902 requires; otherwise when set). Values are written as JSON:
primitives (string, char, bool, byte, sbyte, short, ushort, int, uint, long, ulong, float,
double, decimal, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly) directly; enums and any other type
(Half, Int128, arraysβ¦) through the metadata of your IJsonSerializerContext (register it with
[JsonSerializable], as for bodies; RestConfigurationException otherwise).
Operations
Patch.Add(path, value) // {"op": "add", "path": "...", "value": ...}
Patch.Remove(path) // {"op": "remove", "path": "..."}
Patch.Replace(path, value) // {"op": "replace", "path": "...", "value": ...}
Patch.Move(from, path) // {"op": "move", "from": "...", "path": "..."}
Patch.Copy(from, path) // {"op": "copy", "from": "...", "path": "..."}
Patch.Test(path, value) // {"op": "test", "path": "...", "value": ...}
The operation names are also available as constants (RestSettings.Operation.Add, β¦), and PatchOperation can be
created directly from the operation and the path, with From and Value set by an initializer:
new PatchOperation("replace", "/name") { Value = "Jane" }, new PatchOperation("move", "/b") { From = "/a" }.
PatchOperationJsonContext holds the JSON metadata of PatchOperation and Collection<PatchOperation>.
π Streaming & Paged Responses
// Streamed: one element at a time, as the body arrives
[RestGet("/api/events/stream")]
public sealed partial record StreamEventsRequest : IRestRequestStream<Event>;
using RestResponse response = await client.SendAsync(new StreamEventsRequest());
if (response.Result.GetObjectValue() is IAsyncEnumerable<Event?> events)
{
await foreach (Event? evt in events)
{
ProcessEvent(evt);
}
}
// Paged: the elements and their pagination
[RestGet("/api/events/paged")]
public sealed partial record PagedEventsRequest : IRestRequestStreamPaged<Event>;
using RestResponse paged = await client.SendAsync(new PagedEventsRequest());
if (paged.Result.GetObjectValue() is IAsyncPagedEnumerable<Event?> items)
{
Pagination pagination = await items.GetPaginationAsync(); // before, during or after the enumeration
await foreach (Event? evt in items)
{
ProcessEvent(evt);
}
}
- The elements are read with the
JsonTypeInfo<T>of theSerializerOptionsof yourIJsonSerializerContext. - The response owns the HTTP response and its connection: enumerate before disposing it. The client timeout covers obtaining the response only, so a long-running stream is not cancelled mid-read; the caller's token still is.
- A paged body is an object,
{"items":[β¦],"pagination":{β¦}}, in either order. A body whose root is an array, a string, a number ornullis not a paged body: its enumeration throwsJsonException. An empty body is an empty page. - A
204or a body declared empty has no value at all: test the value before using it. A stream request whose empty body has noContent-LengththrowsJsonExceptionon enumeration. - Response bodies of stream requests are never logged.
- JSON Lines. With
Accept = RestSettings.ContentType.JsonLines(application/jsonl), a server running Xpandables.AspNetCore.AsyncPaged answers a paged request with the items one per line and the pagination in headers: the paged result is read from them (X-Total-Count,X-Page-Size,X-Current-Page, the token of theLink: <β¦>; rel="next"URL),Pagination.Emptywhen the server sent none. A stream request reads a JSON Lines answer (application/jsonlorapplication/x-ndjson) as well. The form read follows the response's content type, so a server that answers JSON is read as before.
[RestGet("/api/events/paged", Accept = RestSettings.ContentType.JsonLines)]
public sealed partial record PagedEventLinesRequest : IRestRequestStreamPaged<Event>;
π‘οΈ Resilience
builder.Services.ConfigureXRestClientOptions(options =>
{
options.Timeout = TimeSpan.FromSeconds(30);
options.Retry = new RestRetryOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromSeconds(1),
MaxDelay = TimeSpan.FromSeconds(30),
UseExponentialBackoff = true,
JitterFactor = 0.2
};
options.CircuitBreaker = new RestCircuitBreakerOptions
{
FailureRatio = 0.1,
BreakDuration = TimeSpan.FromSeconds(30),
SamplingDuration = TimeSpan.FromSeconds(30),
MinimumThroughput = 10
};
});
builder.Services.AddXRestClientWithResilience<IMyApiClient, MyApiClient>(
(sp, client) => client.BaseAddress = new Uri("https://api.example.com"));
AddXRestClientWithResilience adds a resilience handler (RestClientResilience) built from RestClientOptions when
the pipeline is first created: a retry when Retry is set, a circuit breaker when CircuitBreaker is set, and, when a
retry or PerAttemptTimeout is set, a per-attempt timeout: AttemptTimeout for a method that is retried,
PerAttemptTimeout (when set) for the others, none otherwise. It is added once per client: calling the method again for
the same client adds no second handler.
A named client's options start from the options every client shares (services.Configure<RestClientOptions> or
ConfigureXRestClientOptions(configure)), then take ConfigureXRestClientOptions(name, configure). ConfigureXRestClientOptions(configure) is ConfigureAll: it runs for every name in registration order, and again for each named client, so register it before the named configurations and make it assign values. A named client is registered
keyed by its name only, so each client has its own retry, breaker and timeouts:
builder.Services.ConfigureXRestClientOptions(options => options.Timeout = TimeSpan.FromSeconds(30)); // every client
builder.Services.ConfigureXRestClientOptions("payments", options => options.Retry = new RestRetryOptions { MaxRetryAttempts = 2 });
builder.Services.AddXRestClientWithResilience("payments", (_, http) => http.BaseAddress = paymentsUri);
builder.Services.AddXRestClientWithResilience("search", (_, http) => http.BaseAddress = searchUri);
IRestClient payments = provider.GetRequiredKeyedService<IRestClient>("payments");
A named client follows a run-time reload of its options only through a reloadable source of its own name
(Configure<RestClientOptions>(name, section)). An application's own IOptionsFactory<RestClientOptions> replaces the
factory that applies the shared options first.
Long-running requests
An upload or a slow report needs a budget longer than the 30 s default. Give the client a name and its own options:
builder.Services.ConfigureXRestClientOptions("reports", options => options.Timeout = TimeSpan.FromMinutes(10));
builder.Services.AddXRestClientWithResilience("reports", (_, http) =>
{
http.BaseAddress = new Uri("https://reports.example.com");
http.Timeout = TimeSpan.FromMinutes(10);
});
Timeout.InfiniteTimeSpan removes the client's own budget; HttpClient.Timeout (100 s by default) still applies.
A retried method (GET) of a named client that inherits a shared Retry shares the budget between its attempts (10 min / 4 = 2.5 min per attempt by default): set PerAttemptTimeout, or Retry = null, for this client when one attempt may use the whole budget.
RestClientOptions
| Option | Default | Meaning |
|---|---|---|
Timeout |
30 s | Total budget of a send, every retry included (enforced by RestClient); positive and at most about 49.7 days, or Timeout.InfiniteTimeSpan (no budget of the client's own: set HttpClient.Timeout too); ArgumentOutOfRangeException otherwise; the HttpClient.Timeout (100 s by default) and a handler's ConnectTimeout still apply, with the same 408 |
ReadIdleTimeout |
30 s | Longest wait for data in one read of a streamed or binary body, which the caller reads after SendAsync returned (TimeoutException); positive, or Timeout.InfiniteTimeSpan for none |
PerAttemptTimeout |
null |
Timeout of one attempt, for every method; without it a retried method gets AttemptTimeout and the others the whole budget; must be shorter than Timeout for retries to be reachable |
AttemptTimeout |
(computed) | PerAttemptTimeout when set to a positive value; otherwise Timeout divided by the attempts (MaxRetryAttempts + 1 when Retry is set, else 1), never below 1 s; infinite when Timeout is infinite and PerAttemptTimeout is not set |
Retry |
null |
Retry policy; null disables it |
CircuitBreaker |
null |
Circuit breaker policy; null disables it |
ForwardedResponseHeaders |
empty | Response headers copied into Result.Headers besides Location, Retry-After, ETag, Last-Modified, Content-Language, Content-Disposition, WWW-Authenticate, Link |
Logging |
(see Logging) | EnableLogging (true), LogLevel (Information), LogRequestBody / LogResponseBody (false), MaxLoggedBodyLength (4096, also the excerpt of an error body in the failure's exception message), LogQueryString (false) |
RestRetryOptions
| Option | Default | Meaning |
|---|---|---|
MaxRetryAttempts |
3 | Retries after the first attempt |
Delay |
1 s | Base delay |
MaxDelay |
30 s | Upper bound of every delay, Retry-After included |
UseExponentialBackoff |
true |
Exponential (Delay Γ 2^attempt) or constant back-off |
JitterFactor |
0.2 | Randomizes the computed back-off by up to Β± this ratio (0.0 β 1.0) |
RetryableMethods |
GET, HEAD, OPTIONS, TRACE, PUT, DELETE | Methods that may be retried (case-insensitive) |
RetryableStatusCodes |
408, 429, 500, 502, 503, 504 | Statuses that trigger a retry |
IdempotencyKeyHeader |
null |
When set (Idempotency-Key), a POST or PATCH whose body can be sent again gets this header with a GUID, the same on every attempt, and is retried |
Only idempotent methods are retried by default: a POST or PATCH retried after a timeout or a 503 could be applied
twice, since the first attempt may have reached the server. Add a method to RetryableMethods only for endpoints known
to be idempotent; for endpoints that honour an idempotency key, set IdempotencyKeyHeader instead: the key makes a
repeated attempt recognizable. A request whose body cannot be sent again β a non-seekable stream, or a multipart body
with a stream part β is never retried, whatever its method; a seekable stream is rewound to where it stood when the
request was sent, and a string, byte array, JSON or form body (multipart included) is sent again as it is. To retry a
multipart upload, give its file parts as bytes. An exception is retried too, except a cancellation: a cancelled request
is never re-issued. A server's Retry-After (a delay or a date) is honoured, capped at MaxDelay; the jitter applies
to the computed back-off only. A Retry-After that would end after the client's Timeout stops the retries: a
retryable status that carries one (a 429 or 503, for example) is returned with its Retry-After, instead of a
408 after waiting in vain. The idempotency key is already on the message when the request interceptors run: an
interceptor that wants its own key replaces the header (Headers.Remove, then add), while a value set by a header
composer or an IRestHeader request before that is kept.
RestCircuitBreakerOptions
| Option | Default | Meaning |
|---|---|---|
FailureRatio |
0.1 | Failure ratio that opens the circuit |
BreakDuration |
30 s | Time the circuit stays open before half-open |
SamplingDuration |
30 s | Window over which the ratio is computed |
MinimumThroughput |
10 | Requests needed in the window before the circuit can open |
An open circuit surfaces as a 503 failure and is not retried, a per-attempt timeout as a 504, and the overall
Timeout (or the HttpClient.Timeout, or a ConnectTimeout) as a 408.
π Logging
RestClient logs through ILogger<RestClient> (source-generated LoggerMessage):
| Event | Level | Entry |
|---|---|---|
| 1 | Logging.LogLevel |
Sending {Method} request to {Uri} for {RequestName}; the URI without its query unless Logging.LogQueryString |
| 2 | Logging.LogLevel |
Received {StatusCode} response for {RequestName} |
| 6 / 7 | Logging.LogLevel |
Request / response body (opt-in) |
| 4 / 9 | Warning | Request timed out (the client's Timeout / the HTTP stack's timeout) |
| 5 | Error | Request failed with an exception |
| 8 | Debug | Request answered by a request interceptor |
Logging.EnableLogging = false silences these entries. Bodies are logged only with Logging.LogRequestBody
/ Logging.LogResponseBody, only when the logger is enabled at that level, truncated to
Logging.MaxLoggedBodyLength. A request body of unknown length (a non-seekable stream, for example) or that
cannot be rewound, a streamed response and a binary response are never read for a log. RestRequestFactory
logs, at Debug, the interceptor that answered a request.
π§ DI Registration
All registration methods live in Microsoft.Extensions.DependencyInjection (IRestsExtensions).
| Method | Registers |
|---|---|
AddXRestClient(configureClient) / AddXRestClient(name, configureClient) |
IRestClient β RestClient, as a typed HttpClient; a named one is the keyed IRestClient of its name only, built with that name's HttpClient and options |
AddXRestClient<TRestClient>([name,] configureClient) |
IRestClient β your client |
AddXRestClient<TRestClientService, TRestClient>([name,] configureClient) |
Your service interface β your client |
AddXRestClientWithResilience([name,] configureClient) / AddXRestClientWithResilience<TRestClientService, TRestClient>([name,] configureClient) |
The same, plus the resilience handler |
AddXRestTokenProvider<TProvider>() (on the client's IHttpClientBuilder) |
The token provider of that client's secured requests (keyed singleton) and the handler that sends its token |
ConfigureXRestClientOptions(configure) / ConfigureXRestClientOptions(name, configure) |
RestClientOptions of every client / of one named client (after the shared ones) |
AddXRestRequestComposers() |
The eleven request composers (singletons) |
AddXRestResponseComposers() |
The six response composers (singletons) |
AddXRestAttributeProvider() / AddXRestAttributeProvider<T>() |
IRestAttributeProvider (singleton) |
AddXRestRequestFactory() / AddXRestRequestFactory<T>() |
IRestRequestFactory (singleton) |
AddXRestResponseFactory() / AddXRestResponseFactory<T>() |
IRestResponseFactory (singleton) |
AddXRestRequestInterceptor<T>(lifetime) / AddXRestResponseInterceptor<T>(lifetime) |
An interceptor (transient unless a lifetime is passed), once β also after a decoration |
AddXRestAcceptLanguage() |
RestAcceptLanguageInterceptor |
using Microsoft.Extensions.DependencyInjection;
builder.Services
.AddXJsonSerializerContext()
.AddXRestRequestComposers()
.AddXRestResponseComposers()
.AddXRestRequestInterceptor<TenantInterceptor>()
.AddXRestAcceptLanguage();
// A typed client with its own interface, returning the IHttpClientBuilder for further configuration
builder.Services
.AddXRestClient<IMyApiClient, MyApiClient>((sp, client) => client.BaseAddress = new Uri("https://api.example.com"))
.AddXRestTokenProvider<ApiTokenProvider>();
- Every
AddXRestClient*also registers the attribute provider and the request and response factories, only when absent. The parameterlessAddXRestβ¦Provider/Factory()methods add the defaults only when none is registered, and a customAddXRestRequestFactory<MyFactory>()replaces any, so it wins whatever the order of the calls and stays single. - The typed
HttpClientregistration of Microsoft.Extensions.Http is not keyed: several unnamed clients of one service type would be one (the last). Name them, and resolve each withGetRequiredKeyedService<IRestClient>(name), or give each its own service interface (AddXRestClient<TRestClientService, TRestClient>). - The composers are not registered by
AddXRestClient*: callAddXRestRequestComposers()andAddXRestResponseComposers(). The JSON composers need anIJsonSerializerContext(AddXJsonSerializerContext()): without it the composers cannot be resolved, andSendAsyncthrowsRestConfigurationException(wrapping the container'sInvalidOperationException) before anything is sent; a host that validates its container on build fails at startup instead. - A custom client derives from
RestClientor implementsIRestClient.RestClienttakes the factories, theHttpClient, the attribute provider, the caller'sIServiceProvider, and optionallyIOptions<RestClientOptions>and a logger.
Lifetimes and thread safety
The client is a typed HttpClient (transient, its handlers pooled by IHttpClientFactory). The attribute provider, the
factories and the default composers are stateless singletons. Composers and interceptors are resolved for each request
from the services of the caller β the scope that resolved the client β so a scoped or transient component sees the
caller's scope and is never shared between callers. A request built with RestRequestBuilder, and the RestAttribute
a generated Build returns, are immutable and can be shared across threads.
βοΈ Requests Completed by Generation (Native AOT)
Nothing is read by reflection. Xpandables.Rests flows the Xpandables.Generators package, whose RestRequestGenerator
completes each request of your assembly in a generated partial declaration:
- a request declaring a
[Restβ¦]attribute implementsIRestAttributeBuilder:Buildreturns the attribute rebuilt as code, once βRestAttributeis immutable and the generatedBuildreturns one shared instance. Requests deriving from it inherit that builder; one declaring its own attribute re-implements it (the most derived attribute wins, also over aBuildits base implements). A request that implementsBuilditself, or overrides its base's, keeps it. - an
IRestRequestStream<T>/IRestRequestStreamPaged<T>implementsIRestStreamDeserializer<T>/IRestStreamPagedDeserializer<T>, whose default members read the elements with theJsonTypeInfo<T>of yourIJsonSerializerContext(generic requests included). To read them differently, implement the interface on the request.DefaultRestStreamDeserializer<T>andDefaultRestStreamPagedDeserializer<T>expose the same default members, through the interface, for code that deserializes a response outside a request.
Declare those requests partial, and the types containing them: the analyzer reports XRR005 as you type (in generated
code too), and the "Make partial" code fix adds the modifier. A build with RunAnalyzers=false skips that check while
the generator still runs: a request left non-partial then fails when it is sent (RestConfigurationException). A
request declared in an assembly compiled without the generator (F#, Visual Basic) implements IRestAttributeBuilder
by hand; Build(IServiceProvider) receives the caller's services, so it can compute the attribute at run time.
[RestGet("/users/{id}", Location = RestSettings.Location.Path)]
public sealed partial class GetUser : IRestRequestResult<User>, IRestPathString
{
public IDictionary<string, string> GetPathString() => new Dictionary<string, string> { ["id"] = "1" };
}
| Diagnostic | Meaning |
|---|---|
| XRR001 | Error: the attribute cannot be rebuilt by generated code (its type, constructor, a member or an argument type is not accessible from the request): make it accessible, or implement IRestAttributeBuilder. |
| XRR002 | Error: the request is file-local, and a generated partial declaration cannot complete it: make it internal or public. |
| XRR003 | Error: the element type of a stream request is not accessible from the request (an internal type of another assembly): implement IRestStreamDeserializer<T> (or IRestStreamPagedDeserializer<T> for a paged request) on the request, or make the type accessible. |
| XRR004 | Error: several [Restβ¦] attributes on the request: keep one, or implement IRestAttributeBuilder. |
| XRR005 | Error: the request, or a type containing it, is not partial. Code fix: "Make partial". |
Every JSON type the client reads or writes β request bodies, results, streamed elements, non-primitive patch values β
needs metadata in your source-generated JsonSerializerContext; a missing one throws RestConfigurationException
naming the type.
π¦ Package Contents
| Namespace | Types |
|---|---|
System.Rests |
IRestClient, RestClient, RestClientOptions, RestLoggingOptions, RestRetryOptions, RestCircuitBreakerOptions, RestConfigurationException |
System.Rests (requests) |
IRestRequest, IRestRequestResult, IRestRequestResult<T>, IRestRequestStream, IRestRequestStream<T>, IRestRequestStreamPaged, IRestRequestStreamPaged<T>, IRestPathString, IRestQueryString, IRestHeader, IRestCookie, IRestBasicAuthentication, IRestString, IRestPatch, IRestByteArray, IRestStream, IRestFormUrlEncoded, IRestMultipart, RestContentPatch<T>, IPatchOperation, PatchOperation, PatchOperationJsonContext |
System.Rests (attributes) |
RestAttribute, RestGetAttribute, RestPostAttribute, RestPutAttribute, RestDeleteAttribute, RestPatchAttribute, RestHeadAttribute, RestOptionsAttribute, RestTraceAttribute, RestConnectAttribute, RestSettings, IRestAttributeBuilder, IRestAttributeProvider, RestAttributeProvider |
System.Rests (builder) |
RestRequestBuilder, RequestBuilder, ResultRequestBuilder<T>, StreamRequestBuilder<T>, StreamPagedRequestBuilder<T> |
System.Rests (pipeline) |
IRestRequestFactory, RestRequestFactory, IRestResponseFactory, RestResponseFactory, IRestRequestComposer, IRestResponseComposer, IRestRequestInterceptor, IRestResponseInterceptor, RestAcceptLanguageInterceptor, RestRequestContext, RestResponseContext, RestRequest, IRestTokenProvider, RestToken, RestTokenContext, RestUriExtensions |
System.Rests (responses) |
Response (the base, hidden from IntelliSense), RestResponse, RestResponse<TResult>, RestResponseExtensions, IRestStreamDeserializer, IRestStreamDeserializer<T>, IRestStreamPagedDeserializer, IRestStreamPagedDeserializer<T>, DefaultRestStreamDeserializer<T>, DefaultRestStreamPagedDeserializer<T> |
System.Rests.RequestBuilders |
RestRequestBuilderBase, RestPathStringComposer, RestQueryStringComposer, RestHeaderComposer, RestCookieComposer, RestBasicAuthComposer, RestStringComposer, RestByteArrayComposer, RestStreamComposer, RestFormUrlEncodedComposer, RestMultipartComposer, RestPatchComposer |
System.Rests.ResponseBuilders |
RestResponseNoContentComposer, RestResponseContentComposer, RestResponseResultComposer, RestResponseFailureComposer, RestResponseStreamComposer, RestResponseStreamPagedComposer |
Microsoft.Extensions.DependencyInjection |
IRestsExtensions |
π License
Apache License 2.0 β see the LICENSE file for details.
<div align="center">
Built with β€οΈ using .NET 11
</div>
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Extensions.Http (>= 11.0.0)
- Microsoft.Extensions.Http.Resilience (>= 11.0.0)
- Xpandables.AsyncPaged (>= 11.0.1)
- Xpandables.Generators (>= 11.0.1)
- Xpandables.Net (>= 11.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.