Path: redb-route/redb.Route.Http/Fluent/HttpDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Http/Fluent/HttpDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.Http;
///
/// Fluent API for HTTP endpoints.
///
/// .To(Http.Post("api.example.com/users").ContentType("application/xml").Timeout(5000))
/// .To(Http.Get("api.example.com/data").BasicAuth("user", "pass"))
/// .From(Http.Listen("/webhook").Port(8080).Cors())
///
///
public static class Http
{
/// HTTP GET request to the given URL path.
public static HttpBuilder Get(string path) => new("http", path, "GET");
/// HTTP POST request to the given URL path.
public static HttpBuilder Post(string path) => new("http", path, "POST");
/// HTTP PUT request to the given URL path.
public static HttpBuilder Put(string path) => new("http", path, "PUT");
/// HTTP DELETE request to the given URL path.
public static HttpBuilder Delete(string path) => new("http", path, "DELETE");
/// HTTP PATCH request to the given URL path.
public static HttpBuilder Patch(string path) => new("http", path, "PATCH");
/// HTTP HEAD request to the given URL path.
public static HttpBuilder Head(string path) => new("http", path, "HEAD");
/// HTTP consumer — listens for incoming requests on the given route path.
public static HttpBuilder Listen(string path) => new("http", path, null);
}
///
/// Fluent API for HTTPS endpoints.
///
/// .To(Https.Post("secure-api.com/submit").BasicAuth("user", "pass"))
/// .From(Https.Listen("/secure").Port(8443).SslCert("cert.pfx", "pass"))
///
///
public static class Https
{
/// HTTPS GET request to the given URL path.
public static HttpBuilder Get(string path) => new("https", path, "GET");
/// HTTPS POST request to the given URL path.
public static HttpBuilder Post(string path) => new("https", path, "POST");
/// HTTPS PUT request to the given URL path.
public static HttpBuilder Put(string path) => new("https", path, "PUT");
/// HTTPS DELETE request to the given URL path.
public static HttpBuilder Delete(string path) => new("https", path, "DELETE");
/// HTTPS PATCH request to the given URL path.
public static HttpBuilder Patch(string path) => new("https", path, "PATCH");
/// HTTPS HEAD request to the given URL path.
public static HttpBuilder Head(string path) => new("https", path, "HEAD");
/// HTTPS consumer — listens for incoming requests on the given route path.
public static HttpBuilder Listen(string path) => new("https", path, null);
}
///
/// Fluent builder for HTTP/HTTPS endpoint URIs.
///
public sealed class HttpBuilder
{
private readonly string _scheme;
private readonly string _path;
private readonly string? _method;
// Common
private string? _timeout;
private string? _contentType;
// Producer
private bool? _throwOnError;
private bool _skipRequestHeaders;
private bool _skipControlHeaders;
private string? _headerFilterStrategy;
private string? _authScheme;
private string? _authToken;
private string? _username;
private string? _password;
private string? _connectionFactory;
private bool? _followRedirects;
private string? _maxRedirects;
private bool _skipResponseHeaders;
private bool _preserveHostHeader;
// Query-string parameters
private readonly List<(string Name, string Value)> _queryParams = [];
// Host/Port (producer: embedded in URL path; consumer: query params)
private string? _host;
private string? _port;
private string? _methods;
private bool _cors;
private string? _corsOrigins;
private bool _corsCredentials;
private string? _maxRequestBodySize;
private string? _maxConcurrentRequests;
private string? _requestQueueLimit;
private string? _rejectStatusCode;
private string? _retryAfterSeconds;
private string? _protocol;
private bool _ssl;
private string? _sslCertPath;
private string? _sslCertPassword;
private string? _responseCode;
private bool _inOut;
private bool _streamRequest;
private bool _streamResponse;
internal HttpBuilder(string scheme, string path, string? method)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
_scheme = scheme;
_path = path;
_method = method;
}
// ── Common ────────────────────────────────────────────────────────
/// Request/response timeout in milliseconds. Default 30000.
public HttpBuilder Timeout(int ms) { _timeout = ms.ToString(); return this; }
/// Request/response timeout from an expression.
public HttpBuilder Timeout(IExpression timeout) { _timeout = timeout.ToTemplateString(); return this; }
/// Content type. Default "application/json".
public HttpBuilder ContentType(string contentType) { _contentType = contentType; return this; }
// ── Producer ──────────────────────────────────────────────────────
/// Disable throwing on non-success HTTP status codes. Default is to throw.
public HttpBuilder NoThrowOnError() { _throwOnError = false; return this; }
/// Do not map exchange headers to request headers (skipRequestHeaders=true).
public HttpBuilder SkipRequestHeaders() { _skipRequestHeaders = true; return this; }
///
/// Do not let redbHttp.Method / redbHttp.Query on the exchange steer the request
/// (skipControlHeaders=true).
///
public HttpBuilder SkipControlHeaders() { _skipControlHeaders = true; return this; }
///
/// The header filter strategy of the endpoint, by registry name (headerFilterStrategy=#name): an
/// registered in the context.
///
public HttpBuilder HeaderFilterStrategy(string registryName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(registryName);
_headerFilterStrategy = registryName.TrimStart('#');
return this;
}
/// Use HTTP Basic authentication.
public HttpBuilder BasicAuth(IExpression username, IExpression password)
{
_authScheme = "Basic"; _username = username.ToTemplateString(); _password = password.ToTemplateString(); return this;
}
/// Use HTTP Basic authentication (template strings, support ${...}).
public HttpBuilder BasicAuth(string username, string password)
{
_authScheme = "Basic"; _username = username; _password = password; return this;
}
/// Use Bearer token authentication. Token is resolved via AuthToken option at runtime.
public HttpBuilder BearerAuth() { _authScheme = "Bearer"; return this; }
///
/// References a named from the route registry instead of
/// putting Basic/Bearer credentials or the TLS certificate password in the URI.
///
public HttpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Bearer/API-key token value or expression (e.g. Property("jwt")).
public HttpBuilder AuthToken(IExpression token) { _authToken = token.ToTemplateString(); return this; }
/// Bearer/API-key token value (template string, supports ${...}).
public HttpBuilder AuthToken(string token) { _authToken = token; return this; }
/// Disable following HTTP redirects. Default is to follow.
public HttpBuilder NoFollowRedirects() { _followRedirects = false; return this; }
/// Maximum number of redirects to follow. Default 50.
public HttpBuilder MaxRedirects(int max) { _maxRedirects = max.ToString(); return this; }
/// Maximum number of redirects from an expression.
public HttpBuilder MaxRedirects(IExpression max) { _maxRedirects = max.ToTemplateString(); return this; }
/// Do not map response headers to exchange headers (skipResponseHeaders=true).
public HttpBuilder SkipResponseHeaders() { _skipResponseHeaders = true; return this; }
/// Preserve the original Host header when proxying.
public HttpBuilder PreserveHostHeader() { _preserveHostHeader = true; return this; }
// ── Host / Port ────────────────────────────────────────────────────
// Producer: embedded in URL (supports ${...} expressions).
// Consumer: emitted as query params for Kestrel bind config.
///
/// Target host. Producer: part of request URL. Consumer: Kestrel bind address.
///
public HttpBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; }
///
/// Target host (template string, supports ${...}). Producer: part of request URL. Consumer: Kestrel bind address.
///
public HttpBuilder Host(string host) { _host = host; return this; }
///
/// Target port. Producer: part of request URL. Consumer: Kestrel bind port.
///
public HttpBuilder Port(int port) { _port = port.ToString(); return this; }
///
/// Target port from an expression — resolved per message at runtime.
///
public HttpBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
// ── Consumer ──────────────────────────────────────────────────────
/// Comma-separated HTTP methods to accept (e.g. "POST,PUT"). Default: all.
public HttpBuilder Methods(string methods) { _methods = methods; return this; }
/// Enable CORS with optional allowed origins.
public HttpBuilder Cors(string? origins = null) { _cors = true; _corsOrigins = origins; return this; }
/// Allow credentials in CORS requests.
public HttpBuilder CorsCredentials() { _corsCredentials = true; return this; }
/// Maximum request body size in bytes. Default 10 MB.
public HttpBuilder MaxRequestBodySize(long bytes) { _maxRequestBodySize = bytes.ToString(); return this; }
/// Maximum request body size from an expression.
public HttpBuilder MaxRequestBodySize(IExpression bytes) { _maxRequestBodySize = bytes.ToTemplateString(); return this; }
///
/// Admission limit: at most concurrent pipeline executions; overflow
/// beyond the optional FIFO is shed with 429 + Retry-After before
/// any pipeline work (consumer side).
///
public HttpBuilder MaxConcurrentRequests(int max, int queue = 0)
{
_maxConcurrentRequests = max.ToString();
if (queue > 0) _requestQueueLimit = queue.ToString();
return this;
}
/// Status code for a shed request (default 429).
public HttpBuilder RejectStatusCode(int statusCode) { _rejectStatusCode = statusCode.ToString(); return this; }
/// Retry-After value for a shed request in seconds; 0 = do not send (default 1).
public HttpBuilder RetryAfterSeconds(int seconds) { _retryAfterSeconds = seconds.ToString(); return this; }
/// HTTP protocol version: Http1, Http2, Http1And2, Http3, Http1And2And3.
public HttpBuilder Protocol(string protocol) { _protocol = protocol; return this; }
/// Enable SSL/TLS with the given certificate.
public HttpBuilder SslCert(IExpression certPath, IExpression? certPassword = null)
{
_ssl = true; _sslCertPath = certPath.ToTemplateString(); _sslCertPassword = certPassword?.ToTemplateString(); return this;
}
/// Enable SSL/TLS with the given certificate (template strings, support ${...}).
public HttpBuilder SslCert(string certPath, string? certPassword = null)
{
_ssl = true; _sslCertPath = certPath; _sslCertPassword = certPassword; return this;
}
/// Default HTTP response status code. Default 200.
public HttpBuilder ResponseCode(int code) { _responseCode = code.ToString(); return this; }
/// Response status code from an expression.
public HttpBuilder ResponseCode(IExpression code) { _responseCode = code.ToTemplateString(); return this; }
/// Enable request-reply (InOut) exchange pattern.
public HttpBuilder InOut() { _inOut = true; return this; }
/// Enable request body streaming (consumer: body = Stream instead of byte[]).
public HttpBuilder StreamRequest() { _streamRequest = true; return this; }
/// Enable response body streaming (producer: Out body = Stream instead of byte[]).
public HttpBuilder StreamResponse() { _streamResponse = true; return this; }
// ── Query Parameters ──────────────────────────────────────────────
///
/// Adds a query-string parameter to the HTTP request URL.
/// Values containing ${...} are resolved as expressions at runtime.
///
/// Parameter name.
/// Constant value or expression string.
public HttpBuilder Param(string name, object? value)
{
_queryParams.Add((name, value?.ToString() ?? ""));
return this;
}
///
/// Adds a query-string parameter bound to an expression, resolved at runtime.
///
/// Parameter name.
/// Expression that produces the parameter value.
public HttpBuilder Param(string name, IExpression expression)
{
_queryParams.Add((name, expression.ToTemplateString()));
return this;
}
// ── Build ─────────────────────────────────────────────────────────
/// Builds the HTTP/HTTPS endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append(_scheme);
sb.Append(':');
// Producer with explicit Host → embed host[:port] before path
if (_method != null && _host != null)
{
sb.Append(_host);
if (_port != null)
{
sb.Append(':');
sb.Append(_port);
}
if (_path.Length > 0 && _path[0] != '/')
sb.Append('/');
sb.Append(_path);
}
else
{
sb.Append(_path);
}
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolFalse(string key, bool? value) { if (value == false) Append(key, "false"); }
// Method (producer)
AppendIf("method", _method);
// Common
AppendIf("timeout", _timeout);
AppendIf("contentType", _contentType);
// Producer
AppendBoolFalse("throwOnError", _throwOnError);
AppendBool("skipRequestHeaders", _skipRequestHeaders);
AppendBool("skipControlHeaders", _skipControlHeaders);
AppendIf("headerFilterStrategy", _headerFilterStrategy);
AppendIf("authScheme", _authScheme);
AppendIf("authToken", _authToken);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("connectionFactory", _connectionFactory);
AppendBoolFalse("followRedirects", _followRedirects);
AppendIf("maxRedirects", _maxRedirects);
AppendBool("skipResponseHeaders", _skipResponseHeaders);
AppendBool("preserveHostHeader", _preserveHostHeader);
// Consumer host/port as query params (producer embeds them in URL path)
if (_method == null)
{
AppendIf("host", _host);
AppendIf("port", _port);
}
AppendIf("methods", _methods);
AppendBool("cors", _cors);
AppendIf("corsOrigins", _corsOrigins);
AppendBool("corsCredentials", _corsCredentials);
AppendIf("maxRequestBodySize", _maxRequestBodySize);
AppendIf("maxConcurrentRequests", _maxConcurrentRequests);
AppendIf("requestQueueLimit", _requestQueueLimit);
AppendIf("rejectStatusCode", _rejectStatusCode);
AppendIf("retryAfterSeconds", _retryAfterSeconds);
AppendIf("protocol", _protocol);
AppendBool("ssl", _ssl);
AppendIf("sslCertPath", _sslCertPath);
AppendIf("sslCertPassword", _sslCertPassword);
AppendIf("responseCode", _responseCode);
AppendBool("inOut", _inOut);
AppendBool("streamRequest", _streamRequest);
AppendBool("streamResponse", _streamResponse);
// Query parameters
foreach (var (name, value) in _queryParams)
Append($"param.{name}", value);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(HttpBuilder b) => b.Build();
///
public override string ToString() => Build();
}