HTTP Client
- Introduction
- Complete Example: Typed Response and Fake
- Making Requests
- Responses
- Requests in Queued Jobs
- Testing
Introduction
The Http facade is a small, fluent wrapper around IHttpClientFactory for calling other services, modelled on Laravel's HTTP client. Retries are built in; there is no dependency on Polly.
Making Requests
var response = await Http.Get("https://api.example.com/users");
var users = response.Json<List<UserDto>>();The facade has Get, Post, Put, Patch, and Delete. Every request is built with a PendingRequest; start one with a builder method (Http.WithToken(...), Http.Timeout(...), ...) or Http.New() and chain options before sending:
var response = await Http.WithToken(token)
.Timeout(10)
.Retry(3, 100)
.Get("https://api.example.com/users", new { page = 1 });PendingRequest also has Head(url, query).
Request Data
For GET and HEAD, the second argument is added to the query string:
await Http.Get("https://api.example.com/users", new { page = 2, sort = "name" });
// GET https://api.example.com/users?page=2&sort=nameFor POST, PUT, PATCH, and DELETE, the second argument is the body. Objects are sent as JSON by default:
await Http.Post("https://api.example.com/users", new { name = "Ali", role = "admin" });
// Content-Type: application/json; body {"name":"Ali","role":"admin"}Call AsForm() to send application/x-www-form-urlencoded instead (AsJson() switches back):
await Http.AsForm().Post("https://api.example.com/users", new { name = "Ali" });A string body is sent as text/plain, and an HttpContent (for example MultipartFormDataContent) is sent as is.
Raw HttpContent is disposed with its request. Do not combine that same content instance with Retry; use a fresh multipart/content instance for each explicit upload attempt.
Headers
await Http.WithHeaders(new Dictionary<string, string> { ["X-Api-Key"] = key })
.AcceptJson()
.Get("https://api.example.com/me");WithHeaders accepts an anonymous object or a dictionary. Property names are used as header names unchanged, so use a dictionary for names that contain dashes. Accept(contentType) and AcceptJson() set the Accept header.
Authentication
Http.WithToken("t0k3n"); // Authorization: Bearer t0k3n
Http.WithToken("t0k3n", "Token"); // Authorization: Token t0k3nBase URL
Relative URLs are appended to the base URL; absolute URLs are used unchanged:
var github = Http.BaseUrl("https://api.github.com").AcceptJson();
var repo = await github.Get("/repos/dotnet/runtime");A PendingRequest keeps its options, so it can be reused for several calls.
Timeout
Each attempt times out after 30 seconds by default. Set another limit in seconds:
await Http.Timeout(5).Get("https://slow.example.com");Retries
Retry(times, sleepMilliseconds) makes up to times attempts in total, waiting sleepMilliseconds between them:
var response = await Http.Retry(3, 100).Get("https://api.example.com/flaky");A request is retried on a connection error, a timeout, a 5xx response, or a 429 Too Many Requests response. Other 4xx responses are returned immediately.
When the last attempt still gets a 5xx or 429, that response is returned; nothing is thrown. When the last attempt fails with a connection error or a timeout, that exception (HttpRequestException or TaskCanceledException) is thrown.
Error Handling
Unlike .NET's HttpClient.GetFromJsonAsync, and like Laravel, an error status does not throw. Check the response, or call Throw() to turn a 4xx/5xx response into an HttpRequestException (with StatusCode set):
var response = await Http.Get("https://api.example.com/users/1");
if (response.Failed())
{
// ...
}
var user = (await Http.Get("https://api.example.com/users/1")).Throw().Json<UserDto>();Responses
The returned HttpResponse has the whole body already read:
response.Status; // 200
response.Body; // string
response.Json<UserDto>(); // deserialized (camelCase names, case-insensitive)
response.Json(); // JsonNode, or null for an empty body
response.Json()?["name"]; // a single value
response.Header("X-Total"); // header value(s) joined with ", ", or null
response.Successful(); // 2xx
response.Ok(); // 200
response.Redirect(); // 3xx
response.Failed(); // 4xx or 5xx
response.ClientError(); // 4xx
response.ServerError(); // 5xxRequests in Queued Jobs
Inside a queued job, requests are tied to the job's timeout: when the job times out, the request in progress (and any wait between retries) is cancelled, and no further retries are attempted.
Testing
Faking Responses
Http.Fake replaces the client so no real request is sent. Map URL patterns to responses built with Http.Response(body, status, headers); * is a wildcard:
Http.Fake(new()
{
["api.example.com/users*"] = Http.Response(new[] { new { id = 1, name = "Ali" } }, 200,
new Dictionary<string, string> { ["X-Total"] = "1" }),
["api.example.com/broken"] = Http.Response("oops", 500),
});- A pattern is matched, case-insensitively, against the host plus path and query (
api.example.com/users?page=2) and against the full URL. The first matching pattern wins. - Headers whose name starts with
Content-(such asContent-Type) are applied to the response content; other names become response headers. - A string body is returned as is; any other body is returned as JSON.
- A URL that matches no pattern gets an empty
200response.Http.Fake()with no stubs answers every request that way.
The fake only affects the current test (async flow), so tests running in parallel do not interfere.
Inspecting Requests
Every request sent through the fake is recorded with its Method, Url, Headers, and Body. Retries count as separate requests:
var res = await Http.WithToken("t0k3n").Get("https://api.example.com/users", new { page = 2 });
Http.AssertSent(r => r.Url == "https://api.example.com/users?page=2" && r.Headers["Authorization"] == "Bearer t0k3n");
Http.AssertNotSent(r => r.Url.Contains("other.example.com"));
Http.AssertSentCount(1);
Http.AssertNothingSent(); // fails here: one request was sentHttp.Fake() also returns the HttpFake, whose Sent property lists the recorded requests and which has the same assertion methods. Failed assertions throw an InvalidOperationException. See mocking for the other fakes.
Complete Example: Typed Response and Fake
This Blog command defines its DTO and checks the outgoing request without network access:
// app/Commands/HttpDemo.cs
using DotBlaze;
namespace Blog.Commands;
public record RemoteProfile(int Id, string Name);
public class HttpDemo : Command
{
public override string Signature => "demo:http";
public override async Task<int> Handle()
{
Http.Fake(new()
{
["api.example.test/profile"] = Http.Response(new { id = 7, name = "Ada" }),
});
var response = await Http.AcceptJson().Timeout(5)
.Get("https://api.example.test/profile");
var profile = response.Throw().Json<RemoteProfile>()
?? throw new InvalidOperationException("Expected a profile response.");
if (profile.Id != 7 || profile.Name != "Ada")
throw new InvalidOperationException("Unexpected profile data.");
Http.AssertSent(request => request.Method == "GET" &&
request.Url == "https://api.example.test/profile");
Http.AssertSentCount(1);
Line($"{profile.Id}: {profile.Name}");
return 0;
}
}Run dotblaze demo:http: output is 7: Ada. To adapt the calling code to a real service, remove the fake and configure a real trusted endpoint. Throw() handles failed HTTP status codes, connection failures throw before a response exists, and malformed JSON throws during Json<T>(); those are distinct failures. A fake proves request construction and application behavior, not a remote service's availability.