Bundle: redb-route / redb.Route.Http (redb.Route.Http.txt), 25 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Http/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Http;
///
/// Extension methods for registering the HTTP component with dependency injection.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the HTTP and HTTPS components with the route context.
///
public static IServiceCollection AddRedbRouteHttp(this IServiceCollection services)
=> AddRedbRouteHttp(services, null);
///
/// Registers the HTTP and HTTPS components with global CORS configuration.
/// Example: services.AddRedbRouteHttp(cors => { cors.Enabled = true; cors.Origins = "https://example.com"; });
///
/// The service collection.
/// Optional action to configure global CORS defaults for all HTTP consumers.
public static IServiceCollection AddRedbRouteHttp(this IServiceCollection services, Action? configureCors)
{
// Shared server manager — single instance across all route contexts and HTTP-based connectors.
services.AddRedbRouteHttpHosting();
services.AddSingleton(sp =>
{
var component = new HttpComponent();
component.ServerManager = sp.GetRequiredService();
configureCors?.Invoke(component.DefaultCors);
return component;
});
services.AddSingleton(sp =>
{
var component = new HttpsComponent();
component.ServerManager = sp.GetRequiredService();
configureCors?.Invoke(component.DefaultCors);
return component;
});
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
context.AddComponent(sp.GetRequiredService());
context.AddComponent(sp.GetRequiredService());
});
return services;
}
}
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();
}
Path: redb-route/redb.Route.Http/HttpComponent.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/HttpComponent.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Http;
///
/// HTTP/HTTPS component. Schemes: "http", "https".
/// Producer: HttpClient-based HTTP caller (GET/POST/PUT/DELETE/PATCH).
/// Consumer: Kestrel-based embedded HTTP server (webhook receiver).
/// URI format: http:host:port/path?method=POST&timeout=30000
/// URI format: https:api.example.com/orders?method=POST&throwOnError=true
/// URI shorthand: http:GET:/path (method prefix before the path, consumer only)
///
public class HttpComponent : ComponentBase
{
private readonly string _scheme;
///
/// Creates the http component. A parameterless constructor of its own: the assembly scan
/// (context.AddComponents, the Tsak worker's module contexts) creates components through it and skips a type
/// whose only constructor has optional parameters.
///
public HttpComponent() : this("http")
{
}
/// Creates an HTTP component with the specified scheme.
public HttpComponent(string scheme)
{
_scheme = scheme;
}
///
public override string Scheme => _scheme;
///
/// Global CORS defaults applied to all HTTP consumers.
/// Endpoint-level URI parameters (cors, corsOrigins, corsCredentials) override these.
///
public HttpCorsOptions DefaultCors { get; } = new();
///
/// Shared HTTP server manager for pooling Kestrel instances by (host, port).
/// Assigned by AddRedbRouteHttp(); a module host that adds components by scanning leaves
/// it null and keeps the manager in the container instead — see .
///
public SharedHttpServerManager? ServerManager { get; set; }
///
/// The manager a consumer binds on. Resolution order: explicitly assigned → the context's DI
/// singleton → refusal. There is no private fallback on purpose: an http: consumer binds a
/// port, and which port it binds is the host's decision, so a missing manager stays loud (gRPC,
/// AS2, SignalR, WebSocket and SOAP resolve in the same order and end with their own server).
///
internal SharedHttpServerManager Server =>
ServerManager
?? Context.Resolve()
?? throw new InvalidOperationException(
"SharedHttpServerManager is not configured. Register HTTP via AddRedbRouteHttp() in DI, " +
"assign HttpComponent.ServerManager, or give the route context a service provider that holds one.");
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new HttpEndpointOptions();
options.BindFromUri(uri.RawParameters);
// Resolve the named ConnectionFactory right after binding — before the path is parsed, so
// host/port taken from the URI path always win — and before Validate(), which requires
// Username/Password when AuthScheme=Basic.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
// A set-but-unknown name fails loud -- never a silent fallback to URI params.
var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory);
factory.ApplyTo(options, uri);
}
// Support shorthand: http:GET:/path or http:POST:host:port/path
var path = ExtractMethodPrefix(uri.Path, options, uri.RawParameters, out var hasMethodPrefix);
// Extract host[:port] from URI path (e.g. "0.0.0.0:5088/api/demo")
// Only override if not explicitly set via query parameters.
ParseHostPort(path, options, uri.RawParameters);
// Merge global CORS defaults for fields not explicitly set in URI
ApplyCorsDefaults(options, uri.RawParameters);
options.Validate();
return new HttpEndpoint(uri, this, options, path, hasMethodPrefix);
}
///
/// Detects an HTTP method prefix in the URI path (e.g. "GET:/connect/token")
/// and strips it, applying the method to options. Query params always take priority.
/// Returns the cleaned path (without the method prefix).
///
internal static string ExtractMethodPrefix(
string path, HttpEndpointOptions options,
IReadOnlyDictionary rawParams,
out bool hasMethodPrefix)
{
hasMethodPrefix = false;
var colonIdx = path.IndexOf(':');
if (colonIdx <= 0)
return path;
var candidate = path[..colonIdx];
if (!Enum.TryParse(candidate, ignoreCase: true, out var method))
return path;
// Method prefix found — strip it from path
hasMethodPrefix = true;
var cleanPath = path[(colonIdx + 1)..];
// URI query params always take priority
if (!rawParams.ContainsKey("method"))
options.Method = method;
if (!rawParams.ContainsKey("methods"))
options.Methods = candidate.ToUpperInvariant();
return cleanPath;
}
///
/// Extracts host and port from the URI path segment (host[:port][/path]).
/// Only overrides options if not already set via query parameters.
///
private static void ParseHostPort(string path, HttpEndpointOptions options, IReadOnlyDictionary rawParams)
{
// Path format: "host:port/path" or "host/path" or "host:port" or "host"
var segment = path.TrimStart('/');
var slashIdx = segment.IndexOf('/');
var hostPort = slashIdx >= 0 ? segment[..slashIdx] : segment;
var colonIdx = hostPort.LastIndexOf(':');
if (colonIdx > 0)
{
var hostPart = hostPort[..colonIdx];
var portPart = hostPort[(colonIdx + 1)..];
if (!rawParams.ContainsKey("host") && !string.IsNullOrEmpty(hostPart))
options.Host = hostPart;
if (!rawParams.ContainsKey("port") && int.TryParse(portPart, out var port))
options.Port = port;
}
else if (!rawParams.ContainsKey("host") && !string.IsNullOrEmpty(hostPort))
{
options.Host = hostPort;
}
}
///
/// Applies global CORS defaults to options where the URI did not explicitly set them.
/// Endpoint-level parameters always win over component-level defaults.
///
private void ApplyCorsDefaults(HttpEndpointOptions options, IReadOnlyDictionary rawParams)
{
if (!rawParams.ContainsKey("cors"))
options.Cors = DefaultCors.Enabled;
if (!rawParams.ContainsKey("corsOrigins") && DefaultCors.Origins is not null)
options.CorsOrigins ??= DefaultCors.Origins;
if (!rawParams.ContainsKey("corsCredentials"))
options.CorsCredentials = options.CorsCredentials || DefaultCors.Credentials;
// Resolver delegate cannot ride in URI parameters (it is a Func, not a string),
// so we propagate the global default unless the endpoint already set its own.
// BUT: when the URI declared its own static whitelist (corsOrigins=...), the caller
// is making an explicit "this exact origin policy" statement -- injecting a
// component-wide resolver on top would override that intent silently. So we only
// inject the global resolver when the endpoint did not pin its own origins.
if (!rawParams.ContainsKey("corsOrigins"))
options.CorsOriginsResolver ??= DefaultCors.OriginsResolver;
}
}
///
/// HTTPS component. Behaves identically to HTTP but uses the "https" scheme.
///
public class HttpsComponent : HttpComponent
{
/// Creates an HTTPS component.
public HttpsComponent() : base("https") { }
}
///
/// HTTP endpoint. Creates either a producer (HTTP client) or consumer (Kestrel server).
/// The path part of the URI is: host[:port]/path
/// For producer: resolves to target URL.
/// For consumer: path is the route to listen on.
///
public class HttpEndpoint : EndpointBase
{
private readonly string _cleanPath;
private readonly bool _hasMethodPrefix;
/// Creates an HTTP endpoint.
/// Original parsed URI.
/// Parent HTTP component.
/// Parsed endpoint options.
/// Path with method prefix stripped (if any). Falls back to uri.Path.
/// Whether a method prefix was stripped from the path.
public HttpEndpoint(EndpointUri uri, HttpComponent component, HttpEndpointOptions options,
string? cleanPath = null, bool hasMethodPrefix = false)
: base(uri, component, options)
{
_cleanPath = cleanPath ?? uri.Path;
_hasMethodPrefix = hasMethodPrefix;
}
private redb.Route.Core.EndpointHeaderFilter? _headerFilter;
///
/// The header filter strategy of this endpoint on the given side: the one headerFilterStrategy=#name names,
/// or the component's default for that side (). A name the registry does
/// not hold fails here, when the producer or consumer is built.
///
internal redb.Route.Abstractions.IHeaderFilterStrategy HeaderFilterStrategy(EndpointRole role)
=> LazyInitializer.EnsureInitialized(ref _headerFilter,
() => new redb.Route.Core.EndpointHeaderFilter(this, EndpointOptions.HeaderFilterStrategy))
.Or(role == EndpointRole.Producer ? HttpHeaderFilterStrategy.Producer : HttpHeaderFilterStrategy.Consumer);
/// Whether this endpoint uses HTTPS.
public bool IsHttps => Uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase);
/// The scheme prefix for building URLs (http:// or https://).
public string SchemePrefix => IsHttps ? "https://" : "http://";
/// The endpoint options for external access.
internal HttpEndpointOptions EndpointOptions => Options;
///
/// Build the full target URL for the producer.
/// URI path is "host:port/path" or "host/path" — we prepend scheme.
///
public string BuildProducerUrl()
{
var path = _cleanPath.TrimStart('/');
return $"{SchemePrefix}{path}";
}
///
/// The consumer listen path (the route portion after host:port).
/// For "http:0.0.0.0:9090/webhook", returns "/webhook".
/// For "http:0.0.0.0:9090", returns "/".
/// For "http:GET:/webhook", returns "/webhook".
///
public string ConsumerPath
{
get
{
var path = _cleanPath;
// When method prefix was used and path starts with '/',
// it IS the route directly (e.g. "GET:/connect/token" → "/connect/token").
// If it doesn't start with '/', host:port is still present (e.g. "POST:0.0.0.0:8080/api").
if (_hasMethodPrefix && path.StartsWith('/'))
return path;
if (path.StartsWith('/'))
{
// Leading-slash form. Its first segment is an embedded host only in the nonstandard
// "/host:port/route" shape — recognisable because a host[:port] segment contains a ':'
// (route segments never do). Then the route is everything after that segment.
// Otherwise the whole path is the route — which is what the fluent DSL emits:
// Http.Listen("/api/x").Host(..).Port(..) builds "http:/api/x?host=..&port=..", so the
// leading-slash "/api/x" must stay "/api/x", NOT be truncated to "/x".
var rest = path[1..];
var firstSlash = rest.IndexOf('/');
var firstSegment = firstSlash >= 0 ? rest[..firstSlash] : rest;
if (!firstSegment.Contains(':'))
return path;
return firstSlash >= 0 ? rest[firstSlash..] : "/";
}
// Host-first form "host[:port]/route" (or bare "host") — the route starts at the first slash.
var idx = path.IndexOf('/');
return idx >= 0 ? path[idx..] : "/";
}
}
///
public override IProducer CreateProducer()
{
RefuseInboundOptionsOnProducer();
return new HttpProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
RefuseIgnoredInboundCredentials();
var component = (HttpComponent)Component;
return new HttpConsumer(this, processor, Options, component.Server)
{
Authenticator = HttpInboundAuthenticator.Create(Options, component.Context),
};
}
///
/// inboundAuth and its companions say what a CONSUMER requires of its callers; a producer sends a request
/// and checks nobody. Written on a to(...) they would look like protection and do nothing. The message names
/// the parameters, never their values.
///
private void RefuseInboundOptionsOnProducer()
{
var written = redb.Route.Core.EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, EndpointRole.Producer);
if (written.Count == 0)
return;
throw new InvalidOperationException(
$"http producer '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}: these options " +
"tell a consumer which callers to accept, and a producer checks nobody. For the credentials a producer sends, " +
"use authScheme with username/password or authToken.");
}
///
/// authScheme, username and password are what a PRODUCER sends. They share the
/// options class with the consumer, so on a from(...) they used to bind and validate and then
/// check nothing: the endpoint looked closed and was open, with the password sitting in the route
/// key. Refused until the consumer has an inbound check of its own. Only what this URI wrote counts
/// — a named connection factory may carry producer credentials beside the TLS material a consumer
/// reuses it for, and that is not a statement about inbound access. The message names the
/// parameters and never their values. The consumer's own check is inboundAuth.
///
private void RefuseIgnoredInboundCredentials()
{
var written = redb.Route.Core.EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, EndpointRole.Consumer);
if (written.Count == 0)
return;
throw new InvalidOperationException(
$"http consumer '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}, but an " +
"http: consumer does not check callers with them — these options are what a producer sends. As written the endpoint " +
"would accept every caller while looking protected. To check callers, use inboundAuth=basic with " +
"inboundUsername/inboundPassword, or inboundAuth=bearer with tokenValidator=#name.");
}
}
Path: redb-route/redb.Route.Http/HttpConnectionFactory.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/HttpConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
namespace redb.Route.Http;
///
/// Named connection factory for HTTP. Register it in the route registry and reference it by name
/// from the endpoint URI (connectionFactory=my-api) so Basic/Bearer credentials and the TLS
/// certificate password never have to appear in the URI, and therefore can never reach logs,
/// telemetry, or the Tsak dashboard.
///
/// Note: the request/listen address (host and port) is deliberately NOT part of this factory — for
/// the HTTP connector it comes from the endpoint path (http://0.0.0.0:5088/api) and stays
/// there, so a factory can never silently redirect a route to a different host.
///
///
/// Example:
///
/// context.AddToRegistry("billing-api", new HttpConnectionFactory
/// {
/// AuthScheme = HttpAuthScheme.Bearer,
/// AuthToken = Environment.GetEnvironmentVariable("BILLING_TOKEN")
/// });
///
/// // route carries no credentials at all:
/// r.To("http://billing.corp.local/invoices?connectionFactory=billing-api")
///
///
///
public sealed class HttpConnectionFactory
{
/// Authentication scheme (None, Basic, Bearer).
public HttpAuthScheme AuthScheme { get; set; } = HttpAuthScheme.None;
/// Username for Basic auth.
public string? Username { get; set; }
/// Password for Basic auth.
[Sensitive]
public string? Password { get; set; }
///
/// Bearer token for Bearer auth. Supports ${...} expressions exactly like the URI form
/// (e.g. ${env:BILLING_TOKEN}, ${header.jwt}) — an expression is resolved per
/// request, a plain value is used as-is.
///
[Sensitive]
public string? AuthToken { get; set; }
/// Request timeout in milliseconds (default 30000).
public int Timeout { get; set; } = 30_000;
/// Serve/connect over TLS.
public bool Ssl { get; set; }
/// Path to the TLS certificate.
public string? SslCertPath { get; set; }
/// Password for the TLS certificate.
[Sensitive]
public string? SslCertPassword { get; set; }
///
/// Copies this factory's authentication and TLS settings onto the endpoint options, but only
/// for parameters the endpoint URI did not set explicitly — an inline URI value always wins,
/// so existing routes keep their behaviour.
///
internal void ApplyTo(HttpEndpointOptions options, EndpointUri uri)
{
var supplied = uri.RawParameters;
if (!supplied.ContainsKey(nameof(options.AuthScheme))) options.AuthScheme = AuthScheme;
if (!supplied.ContainsKey(nameof(options.Username))) options.Username = Username;
if (!supplied.ContainsKey(nameof(options.Password))) options.Password = Password;
if (!supplied.ContainsKey(nameof(options.AuthToken)) && AuthToken is not null)
{
// Mirror EndpointOptions.BindDynamicValue: a ${...} value becomes a per-request
// expression, anything else is wrapped as a static value.
options.AuthToken = AuthToken.Contains("${", StringComparison.Ordinal)
? DynamicValue.FromExpression(new StringExpression(AuthToken))
: DynamicValue.FromStatic(AuthToken);
}
if (!supplied.ContainsKey(nameof(options.Timeout))) options.Timeout = Timeout;
if (!supplied.ContainsKey(nameof(options.Ssl))) options.Ssl = Ssl;
if (!supplied.ContainsKey(nameof(options.SslCertPath))) options.SslCertPath = SslCertPath;
if (!supplied.ContainsKey(nameof(options.SslCertPassword)))
options.SslCertPassword = SslCertPassword;
}
}
Path: redb-route/redb.Route.Http/HttpConsumer.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/HttpConsumer.cs
----
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using System.Diagnostics;
using System.Linq;
namespace redb.Route.Http;
///
/// HTTP consumer. Uses SharedHttpServerManager to register routes on a shared
/// Kestrel server instance per (host, port). Multiple consumers can serve
/// different routes on the same port.
/// Supports configurable bind address, CORS, allowed methods, HTTPS/TLS,
/// request body streaming, and InOut exchange patterns for synchronous responses.
///
public class HttpConsumer : IConsumer
{
private readonly HttpEndpoint _endpoint;
public IEndpoint Endpoint => _endpoint;
private readonly IProcessor _processor;
private readonly HttpEndpointOptions _options;
private readonly redb.Route.Abstractions.IHeaderFilterStrategy _headerFilter;
private readonly SharedHttpServerManager _serverManager;
private ILogger? _logger;
private RouteRegistration? _registration;
private long _processedCount;
// Unregistering the route only stops NEW requests from reaching it. When another route still
// holds the port, the listener stays up and nobody waits for the ones already in the pipeline,
// so a deploy that removes one route cuts its requests mid-flight. Same guard every broker
// consumer uses.
private readonly InflightDrainGuard _drain = new();
/// Creates an HTTP consumer.
public HttpConsumer(HttpEndpoint endpoint, IProcessor processor, HttpEndpointOptions options, SharedHttpServerManager serverManager)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_serverManager = serverManager ?? throw new ArgumentNullException(nameof(serverManager));
_logger = (endpoint.Component as ComponentBase)?.Logger;
_headerFilter = endpoint.HeaderFilterStrategy(EndpointRole.Consumer);
}
/// The inbound check (inboundAuth); null when the endpoint accepts every caller.
internal HttpInboundAuthenticator? Authenticator { get; init; }
// Each request header exactly as received (the object put on the exchange), so the response can tell a value the
// client sent from one the route wrote under the same name.
private const string RequestHeaderValuesKey = "redbHttp.RequestHeaderValues";
/// Number of requests successfully processed.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// The base URL the server is listening on. Available after Start().
public string? BaseUrl { get; private set; }
///
public async Task Start(CancellationToken ct = default)
{
_drain.Start(ct);
var host = _options.Host;
var port = _options.Port;
var path = _endpoint.ConsumerPath;
var ssl = _options.Ssl;
// Translate the per-endpoint CORS knobs into a per-route CORS policy. The shared server
// installs ONE CORS dispatch middleware per (host, port) which selects the policy by
// the matched route, so different endpoints on the same port may declare different
// policies (resolves the legacy "first-wins" gotcha; see SharedHttpServerManager).
RouteCorsOptions? corsOptions = null;
if (_options.Cors)
{
// Validation in HttpEndpointOptions.Validate guarantees that at least one of
// CorsOrigins / CorsOriginsResolver is supplied here -- no implicit "*" fallback.
corsOptions = new RouteCorsOptions(
AllowedOrigins: _options.CorsOrigins,
AllowedMethods: _options.Methods,
AllowCredentials: _options.CorsCredentials,
OriginsResolver: _options.CorsOriginsResolver);
}
_registration = _serverManager.RegisterRoute(
host, port, path, _options.Methods, HandleRequest,
ssl, _options.SslCertPath, _options.SslCertPassword,
corsOptions, _options.MaxRequestBodySize, _options.Protocol,
concurrencyLimit: ConcurrencyLimitOptions.FromEndpoint(
_options.MaxConcurrentRequests, _options.RequestQueueLimit,
_options.RejectStatusCode, _options.RetryAfterSeconds,
onRejected: _endpoint.RecordRejected));
try
{
await _serverManager.EnsureStarted(host, port, ct).ConfigureAwait(false);
}
catch
{
// The listener did not come up (a port still taken): the route leaves it, so a later Start registers
// once and does not find a stale registration of its own.
await Stop(CancellationToken.None).ConfigureAwait(false);
throw;
}
BaseUrl = _serverManager.GetBaseUrl(host, port);
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("HTTP consumer started: {Url}", BaseUrl + path);
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_registration is not null)
{
var host = _options.Host;
var port = _options.Port;
_serverManager.UnregisterRoute(_registration);
_registration = null;
// New requests can no longer reach this route; the ones inside it still can finish.
await _drain.DrainAsync(ct, _logger, $"http://{host}:{port}{_endpoint.ConsumerPath}").ConfigureAwait(false);
await _serverManager.StopIfEmpty(host, port, ct).ConfigureAwait(false);
}
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("HTTP consumer stopped: {Host}:{Port}", _options.Host, _options.Port);
}
private async Task HandleRequest(HttpContext httpContext)
{
// The server span of the request, as every inbound transport opens one: the caller's trace goes on from
// traceparent, or from the host's own span when ASP.NET Core instrumentation opened it, and the route's spans
// sit under this one. It covers the whole request, the refused ones too.
using var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{httpContext.Request.Method} {_endpoint.ConsumerPath}", ActivityKind.Server,
"http.method", httpContext.Request.Method, _endpoint.Uri.NormalizedKey,
httpContext.Request.Headers, static (headers, name) => headers.TryGetValue(name, out var value) ? value.ToString() : null,
InboundParent.HostRequest);
try
{
await HandleTracedRequest(httpContext, span.Activity).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !httpContext.RequestAborted.IsCancellationRequested)
{
span.Activity.RecordFailure(ex);
throw;
}
finally
{
if (span.Activity is { } activity)
{
var status = httpContext.Response.StatusCode;
if (activity.IsAllDataRequested)
activity.SetTag("http.response.status_code", status);
// A server span is an error for a 5xx only: a 4xx is the caller's mistake, answered correctly.
if (status >= 500 && activity.Status != ActivityStatusCode.Error)
activity.SetStatus(ActivityStatusCode.Error);
}
}
}
private async Task HandleTracedRequest(HttpContext httpContext, Activity? span)
{
// The inbound check comes first: a refused request is answered with 401 and no exchange is built for it.
System.Security.Claims.ClaimsPrincipal? authenticated = null;
if (Authenticator is not null)
{
authenticated = await Authenticator.AuthenticateAsync(httpContext).ConfigureAwait(false);
if (authenticated is null)
return;
}
// Build exchange from HTTP request
var exchange = await BuildExchange(httpContext).ConfigureAwait(false);
if (authenticated is not null)
{
// The credentials stop at the check: a route that logs, forwards or echoes its headers must not carry them on.
exchange.In.Headers.Remove(HeaderNames.Authorization);
if (exchange.Properties.TryGetValue("redbHttp.RequestHeaderNames", out var names) && names is ISet requestHeaders)
requestHeaders.Remove(HeaderNames.Authorization);
ExchangePrincipal.Set(exchange, authenticated);
}
// Set exchange pattern
exchange.Pattern = _options.InOut ? ExchangePattern.InOut : ExchangePattern.InOnly;
_drain.Increment();
try
{
// Process through the route pipeline
try
{
await _processor.Process(exchange, httpContext.RequestAborted).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !httpContext.RequestAborted.IsCancellationRequested)
{
_logger?.LogError(ex, "HTTP request processing failed: {Method} {Path}",
httpContext.Request.Method, httpContext.Request.Path);
exchange.Exception ??= ex;
}
// Check for exceptions
if (exchange.Exception is not null && !exchange.ExceptionHandled)
{
// The exception's own text goes to the log, never to the caller: it is written by
// whoever threw it and routinely carries a file path, a connection string or the name
// of an inner service (BR-4). The caller gets the exchange id to quote instead — the
// same id the log line above carries, so an operator can find the real reason.
_logger?.LogError(exchange.Exception,
"Route failed for {Method} {Path} (exchange {ExchangeId})",
httpContext.Request.Method, httpContext.Request.Path, exchange.ExchangeId);
span.RecordFailure(exchange.Exception);
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "text/plain; charset=utf-8";
await httpContext.Response.WriteAsync(
$"An unexpected error occurred while processing the request (ref: {exchange.ExchangeId}).",
httpContext.RequestAborted).ConfigureAwait(false);
return;
}
// Build HTTP response from exchange
try
{
await WriteResponse(httpContext, exchange).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger?.LogError(ex,
"HTTP response writing failed: {Method} {Path}, route={RouteId}, statusStarted={Started}",
httpContext.Request.Method, httpContext.Request.Path, exchange.RouteId, httpContext.Response.HasStarted);
throw;
}
Interlocked.Increment(ref _processedCount);
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
_drain.Decrement();
}
}
private async Task BuildExchange(HttpContext httpContext)
{
var request = httpContext.Request;
// Read request body
object? body = null;
if (request.ContentLength > 0 || request.ContentType is not null)
{
if (_options.StreamRequest)
{
// Stream passthrough — body stays as HttpRequest.Body stream.
// Exchange.DisposeAsync does NOT own this stream (Kestrel does),
// but the stream remains valid until WriteResponse completes.
body = request.Body;
}
else
{
using var ms = new MemoryStream();
await request.Body.CopyToAsync(ms, httpContext.RequestAborted).ConfigureAwait(false);
body = ms.ToArray();
}
}
var message = new Message(body);
// Set ContentType from HTTP request
if (!string.IsNullOrEmpty(request.ContentType))
message.ContentType = request.ContentType;
// Map HTTP request headers to exchange headers
message.Headers[HttpHeaders.Method] = request.Method;
message.Headers[HttpHeaders.Path] = request.Path.Value ?? "/";
message.Headers[HttpHeaders.Url] = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
message.Headers[HttpHeaders.Port] = _options.Port;
if (request.QueryString.HasValue)
{
message.Headers[HttpHeaders.Query] = request.QueryString.Value?.TrimStart('?') ?? string.Empty;
// Extract individual query parameters as redbHttp.QueryParam.*
foreach (var qp in request.Query)
{
message.Headers[$"{HttpHeaders.QueryParamPrefix}{qp.Key}"] = qp.Value.Count switch
{
0 => string.Empty,
1 => (object)qp.Value[0]!,
_ => string.Join(",", qp.Value!)
};
}
}
// Extract route template parameters as redbHttp.RouteParam.*
if (httpContext.Items.TryGetValue("__redbRouteValues", out var rvObj) && rvObj is RouteValueDictionary routeValues)
{
foreach (var (key, value) in routeValues)
{
if (value is not null)
message.Headers[$"{HttpHeaders.RouteParamPrefix}{key}"] = value;
}
}
if (httpContext.Connection.RemoteIpAddress is not null)
{
message.Headers[HttpHeaders.RemoteAddress] = httpContext.Connection.RemoteIpAddress.ToString();
}
// The exchange the header filter strategy is asked about; the headers below go into its message.
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
// Copy all HTTP headers to exchange, and remember which ones came from
// the request so they are not accidentally echoed in the response.
var requestHeaderNames = new HashSet(StringComparer.OrdinalIgnoreCase);
var requestHeaderValues = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var header in request.Headers)
{
// Skip pseudo-headers
if (header.Key.StartsWith(':')) continue;
// Transport-owned headers are set above from the connection itself, and processors trust
// them: redbHttp.RemoteAddress drives rate limiting, brute-force lockout and audit. This copy
// runs AFTER those assignments, so without the guard a caller sending a header literally
// named "redbHttp.RemoteAddress" (a valid HTTP token) would overwrite the socket address and
// pick its own throttle bucket.
if (HttpHeaders.IsRedbHeader(header.Key)) continue;
// A response field in a request is dropped here, at the transport: the route never sees a client's value
// under a name it may later write for the response (Set-Cookie, Location, WWW-Authenticate, ...).
if (HttpHeaders.ResponseOnlyHeaders.Contains(header.Key)) continue;
var received = header.Value.Count switch
{
0 => string.Empty,
1 => (object)header.Value[0]!,
_ => string.Join(", ", header.Value!)
};
if (_headerFilter.FilterIncoming(header.Key, received, exchange)) continue;
requestHeaderNames.Add(header.Key);
message.Headers[header.Key] = received;
requestHeaderValues[header.Key] = received;
}
exchange.Properties["redbHttp.RequestHeaderNames"] = requestHeaderNames;
exchange.Properties[RequestHeaderValuesKey] = requestHeaderValues;
ExchangePrincipal.Set(exchange, SharedHttpServerManager.GetResolvedPrincipal(httpContext));
return exchange;
}
private async Task WriteResponse(Microsoft.AspNetCore.Http.HttpContext httpContext, IExchange exchange)
{
// Pick the response message: Out if set, otherwise In (pipeline merges Out→In)
var responseMsg = exchange.HasOut ? exchange.Out! : exchange.In;
// Determine status code: header override > fallback > options default
var statusCode = _options.ResponseCode;
if (responseMsg.Headers.TryGetValue(HttpHeaders.ResponseCode, out var rc))
{
if (rc is int code) statusCode = code;
else if (rc is string codeStr && int.TryParse(codeStr, out var parsed)) statusCode = parsed;
}
else if (responseMsg.Headers.TryGetValue("status.code", out var sc))
{
// Fallback: controller dispatchers set "status.code" for transport-agnostic status
if (sc is int code2) statusCode = code2;
else if (sc is string scStr && int.TryParse(scStr, out var parsed2)) statusCode = parsed2;
}
httpContext.Response.StatusCode = statusCode;
// Set Content-Type
var responseContentType = responseMsg.ContentType ?? _options.ContentType;
if (responseMsg.Headers.TryGetValue(HttpHeaders.ResponseContentType, out var rct) && rct is string rctStr)
{
responseContentType = rctStr;
}
// InOut pattern — propagate headers and (optionally) body.
// NOTE: headers MUST be copied even when Body is null. Otherwise body-less
// responses (HTTP 302 redirects, 204 No Content, Set-Cookie-only replies)
// silently drop Location / Set-Cookie / etc. See repo memory
// 'http-redirect-headers-bug' for the symptom history.
if (_options.InOut)
{
httpContext.Response.ContentType = responseContentType;
// Copy response headers (always, regardless of body presence).
// When the response message is exchange.In, it still contains the original request headers. Never echo
// those back — but only a value that is still the one the client sent. Matching by name let a client
// suppress a header the route wrote: a request carrying Cache-Control removed the route's no-store.
var requestHeaderValues =
exchange.Properties.TryGetValue(RequestHeaderValuesKey, out var valuesObj)
&& valuesObj is Dictionary received
? received
: null;
foreach (var (key, value) in responseMsg.Headers)
{
if (requestHeaderValues is not null && requestHeaderValues.TryGetValue(key, out var sent)
&& ReferenceEquals(sent, value)) continue;
// The protocol fields and the component's own namespace are the transport's, whatever the strategy says.
if (HttpHeaders.ProtocolHeaders.Contains(key)) continue;
if (HttpHeaders.IsRedbHeader(key)) continue;
if (_headerFilter.FilterOutgoing(key, value, exchange)) continue;
if (value is null) continue;
// Headers like Set-Cookie can carry multiple values. Use StringValues so
// ASP.NET emits one header line per entry instead of stringifying the array.
Microsoft.Extensions.Primitives.StringValues sv = value switch
{
string s => s,
string[] arr => arr,
System.Collections.IEnumerable seq when value is not string =>
seq.Cast