Csharpessentials http

From senrecep/CSharpEssentials · View interactive version

Csharpessentials http is an AI agent skill from the GitHub repository senrecep/CSharpEssentials. Use when making HTTP calls that should return Result/Result<T> instead of throwing. Covers GetFromJsonAsResultAsync, PostAsJsonAsResultAsync, PutAsJsonAsResultAsync, PatchAsJsonAsResultAsync, DeleteAsResultAsync, SendAsResultAsync on HttpClient, the fluent HttpRequestBuilder (WithHeader, WithQuery,

How to use this skill

Skill file

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));

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));

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());

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);
    });
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.