CSharpEssentials.Http
HttpClient extensions that return Result / Result<T> instead of throwing on 4xx/5xx or transport errors.
Installation
dotnet add package CSharpEssentials.Http
Namespace
using CSharpEssentials.Http;
using CSharpEssentials.ResultPattern; // Result, Result<T>
using CSharpEssentials.Resilience; // ResiliencePolicy (for the resilience helpers)
Result-returning extensions
All methods take a Uri (use UriKind.Relative with a BaseAddress).
HttpClient client = new() { BaseAddress = new Uri("https://api.example.com") };
Result<User> user = await client.GetFromJsonAsResultAsync<User>(new Uri("/users/1", UriKind.Relative));
Result<User> created = await client.PostAsJsonAsResultAsync<User>(
new Uri("/users", UriKind.Relative),
new { Name = "Alice", Age = 30 });
Result<User> updated = await client.PutAsJsonAsResultAsync<User>(new Uri("/users/1", UriKind.Relative), new { Name = "Alice" });
Result<User> patched = await client.PatchAsJsonAsResultAsync<User>(new Uri("/users/1", UriKind.Relative), new { Age = 31 });
Result deleted = await client.DeleteAsResultAsync(new Uri("/users/1", UriKind.Relative));
- 2xx → success. A 2xx whose body is the JSON literal
null→NotFounderror. An empty or malformed JSON body, or a request value that fails to serialize →Validationerror. - Non-2xx →
HttpStatusCodeMapper.ToError(statusCode): codeHttp.<status>, type fromToErrorType(400/411/413-417/422 →Validation, 401/407 →Unauthorized, 403 →Forbidden, 404/410 →NotFound, 409/412/429 →Conflict, 408 and 5xx →Unexpected, 402/405/406 and any other status →Failure). - Transport exceptions →
Unexpectederror. Cancelling your own token throwsOperationCanceledException; an HTTP timeout (TaskCanceledExceptionwrappingTimeoutException, e.g.HttpClient.Timeout) →Unexpectederror with codeHttp.Timeout(a PollyTimeoutRejectedExceptionkeeps its type name as code), and any other cancellation →Unexpectederror (both threw before 6.5.0). - JSON uses
EnhancedJsonSerializerOptions.DefaultOptionsunless you passoptions. For trimming or Native AOT, use theJsonTypeInfo<T>overloads (client.GetFromJsonAsResultAsync(uri, AppJsonContext.Default.User),WithJsonTypeInfoContent); passing a literalnullas options is ambiguous with them. - Also available:
PostAsResultAsync/PutAsResultAsync(rawHttpContent),SendAsResultAsync/SendAsResultAsync<T>(HttpRequestMessage),SendWithRedirectsAsResultAsync, andHttpContent.ReadAsStringAsResultAsync/ReadFromJsonAsResultAsync<T>.
HttpRequestBuilder
Result<User> result = await HttpRequestBuilder
.Get("https://api.example.com/users/1")
.WithHeader("Accept", "application/json")
.WithQuery("include", "profile")
.AsResultAsync<User>(client);
Result posted = await HttpRequestBuilder
.Post("/users")
.WithJsonContent(new { Name = "Bob" })
.AsResultAsync(client);
Result<User> redirected = await HttpRequestBuilder
.Get("/legacy-url")
.FollowRedirects(maxRedirects: 3)
.AsResultAsync<User>(client);
Factories: Get, Post, Put, Patch, Delete (string or Uri). Builders: WithMethod, WithUri, WithHeader, WithHeaders, WithQuery (name/value, dictionary or object value), WithRoute (fills {name} placeholders), WithEnumConventions, WithContent, WithJsonContent, WithJsonTypeInfoContent, WithIdempotencyKey, FollowRedirects (default 5 hops). Build() returns Result<HttpRequestMessage>.
WithQuery and Uri.WithQueryString work with relative and absolute URIs: .Get("/users/1").WithQuery("include", "profile") builds /users/1?include=profile, merged with any existing query and placed before a fragment. Relative request URIs resolve against BaseAddress.
Query strings
Uri uri = new("https://api.example.com/search");
Result<Uri> single = uri.WithQueryString("q", "csharp");
Result<Uri> fromDictionary = uri.WithQueryString(new Dictionary<string, string?> { ["page"] = "1" });
Result<Uri> fromObject = uri.WithQueryString(new { q = "csharp", page = 2 });
Result<string> query = new { q = "csharp" }.ToQueryString();
Resilience
Backed by CSharpEssentials.Resilience and Polly.Core 8 (not the full Polly package).
ResiliencePolicy policy = HttpClientResilienceExtensions.CreateResiliencePolicy(
maxRetryAttempts: 3,
timeout: TimeSpan.FromSeconds(30));
Result<User> result = await policy.ExecuteAsync(token =>
client.GetFromJsonAsResultAsync<User>(new Uri("/users/1", UriKind.Relative), cancellationToken: token));
- Policies:
CreateRetryPolicy,CreateTimeoutPolicy,CreateCircuitBreakerPolicy,CreateResiliencePolicy(plus generic<T>forms). - Raw Polly pipelines:
CreateRetryPipeline,CreateTimeoutPipeline,CreateCircuitBreakerPipeline,CreateResiliencePipeline, run withpipeline.ExecuteAsResultAsync(...). - Failed
Resultvalues are retried like exceptions, exceptUnauthorized,Forbidden,NotFoundandValidationerrors.maxRetryAttemptscounts retries after the first attempt; theCreateResiliencePolicy/CreateResiliencePipelinetimeout defaults to 30 s.
Idempotency-Key client
Retry POST/PATCH only when every attempt carries the same Idempotency-Key. Set the key once per logical call; the retry resends the same HttpRequestMessage, so the key stays the same.
string key = request.SetIdempotencyKey(); // generated, or pass IdempotencyKeys.For(...)
Result<Payment> paid = await HttpRequestBuilder.Post("/payments")
.WithJsonContent(payment)
.WithIdempotencyKey() // made now; every Build() reuses it
.AsResultAsync<Payment>(client);
services.AddHttpClient("payments")
.AddIdempotencyKeys() // optional, .NET 9+; before the resilience handler
.AddStandardResilienceHandler(o => o.Retry.RetryUnsafeMethodsOnlyWithIdempotencyKey());
IdempotentRetry.ShouldRetryAsync(request, response, exception, options, cancellationToken)is the decision;RetryUnsafeMethodsOnlyWithIdempotencyKey()plugs it into anyRetryStrategyOptions<HttpResponseMessage>.- Never retried:
Idempotency-Replayed: true, caller cancellation, POST/PATCH without a key, 400/422 key errors, business 409s, 2xx,SsrfBlockedException. - POST/PATCH with a key retry on no response or timeout, 408, 429, 503, 504, and 409
Idempotency.InFlight. A 409 InFlight, 429 or 503 waits for itsRetry-After(capped byIdempotentRetryOptions.MaxRetryAfter, 30 s); without it the normal backoff applies. 500/502 are not retried for them; GET/HEAD/PUT/DELETE/OPTIONS also retry every 5xx. - The 409 body is read up to 4 KiB within
ProblemReadTimeout(2 s) and put back; an unreadable or stuck body is not retried. Microsoft.Extensions.Http.Resilienceis your own reference. The request comes fromresponse.RequestMessage; only when no response arrived is it read fromIdempotentRetry.RequestMessageKey, so in a pipeline you run yourself, setcontext.Properties.Set(IdempotentRetry.RequestMessageKey, request).
SSRF guard (.NET 9+, not available on netstandard2.1)
Use it for any client that calls a URL a user or tenant supplied (webhooks, link previews, import-by-URL).
services.AddHttpClient("webhooks")
.AddSsrfGuard(o =>
{
o.MaxResponseContentLength = 1_048_576;
o.Timeout = TimeSpan.FromSeconds(10);
});
- Defaults: https only on port 443, at most 3 redirects, no proxy, no cookie container, never HTTP/3 (QUIC skips
ConnectCallback). Private, loopback, link-local, metadata, multicast and reserved IPv4/IPv6 ranges are blocked, including Teredo, ORCHID (2001:10::/28), benchmarking (2001:2::/48), documentation (2001:db8::/32,3fff::/20), SRv6 SIDs (5f00::/16), discard-only (100::/64), SIIT (::ffff:0:0:0/96), 6to4 relay anycast (192.88.99.0/24),fec0::/10,64:ff9b:1::/48and IPv6 forms that embed a blocked IPv4 address. - Every resolved address is checked, and the socket connects to an address that was checked. A name with even one private address is rejected.
- Every redirect hop is checked again.
Authorization,Proxy-AuthorizationandCookieare removed on cross-origin hops. - Exceptions:
AllowedNetworks/BlockedNetworks(IPNetwork.Parse("10.0.0.0/8")) andAllowedHosts/BlockedHosts("*.example.com"matches subdomains, notexample.com; case, trailing dot and IDN form are normalized). Block lists win. Use host wildcards only for domains whose DNS you control. - Custom rules: set
options.AddressPolicy/options.RequestPolicyfor one client, or registerIOutboundAddressPolicy/IOutboundRequestPolicyin DI for every guarded client. Options win over the container. - A blocked request throws
SsrfBlockedException(Reason,BlockedAddress; the message never contains the resolved address). The*AsResultAsyncextensions returnErrorType.Forbiddenwith codeHttp.SsrfBlockedandreasonmetadata, also forTimeoutandResponseTooLarge. While buffering a body it may arrive wrapped in anHttpRequestException; check theInnerExceptionchain. - Do not retry
SsrfBlockedExceptionin resilience handlers. - Do not replace the primary handler or turn on a proxy or cookies after
AddSsrfGuard; the first request will throw.