Path: redb-route/redb.Route.Controllers/HttpControllerDispatcher.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.Controllers/HttpControllerDispatcher.cs ---- using System.Reflection; using System.Text.Encodings.Web; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Controllers; /// /// Dispatches HTTP requests to controller methods using REST conventions. /// Reads redbHttp.Method and redbHttp.Path headers set by the HTTP consumer, /// resolves controller actions from the , /// and binds parameters from route templates, query strings, and request body. /// /// This is the HTTP-native equivalent of /// that works directly with the headers produced by the HTTP consumer — /// no manual header translation required. /// /// public sealed class HttpControllerDispatcher : IProcessor { private readonly ControllerRegistry _registry; private readonly IRouteContext _context; private readonly JsonSerializerOptions _jsonOptions; private readonly ILogger? _logger; // Headers set by HttpConsumer (string constants to avoid dependency on redb.Route.Http) internal const string HttpMethodHeader = "redbHttp.Method"; internal const string HttpPathHeader = "redbHttp.Path"; internal const string RouteParamPrefix = "redbHttp.RouteParam."; internal const string QueryParamPrefix = "redbHttp.QueryParam."; /// /// Default JSON serializer options used when no custom options are supplied. /// camelCase property naming matches the de-facto HTTP API convention /// (Google/Microsoft REST style guides, JSON:API, ASP.NET Core default) and /// stays consistent with . /// /// Uses so non-ASCII /// (Cyrillic, emoji, diacritics) and ASCII punctuation like " are emitted /// as-is in UTF-8 instead of being escaped to \u0022/\u0410. This is /// safe for HTTP API responses; it's only unsafe when embedding JSON directly /// inside HTML/JS, which dispatcher output never does. /// /// private static readonly JsonSerializerOptions DefaultJsonOptions = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; /// Controller registry with registered actions. /// Route context for controller instantiation. /// /// Optional JSON serializer options used for body (de)serialization and the dispatcher's /// own error envelope. When null, camelCase defaults are used. Pass a custom /// instance to override naming policy / converters / etc. for a given mount point. /// public HttpControllerDispatcher( ControllerRegistry registry, IRouteContext context, JsonSerializerOptions? jsonOptions = null) { _registry = registry ?? throw new ArgumentNullException(nameof(registry)); _context = context ?? throw new ArgumentNullException(nameof(context)); _jsonOptions = jsonOptions ?? DefaultJsonOptions; _logger = ControllerErrorReporting.CreateLogger(context); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var method = exchange.In.GetHeader(HttpMethodHeader); var path = exchange.In.GetHeader(HttpPathHeader); if (string.IsNullOrEmpty(method) || string.IsNullOrEmpty(path)) { WriteError(exchange, 400, "BadRequest", $"Missing required headers: {HttpMethodHeader} and/or {HttpPathHeader}"); return; } // Strip leading slash — registry templates don't use it (e.g. "modules/42", not "/modules/42") var normalizedPath = path.StartsWith('/') ? path[1..] : path; var action = _registry.Resolve(method, normalizedPath, out var routeParams); if (action is null) { WriteError(exchange, 404, "NotFound", $"No action matches {method} {path}"); return; } // Merge redbHttp.RouteParam.* headers into routeParams (consumer extracts these from templates) MergeHttpRouteParams(exchange, routeParams); // The boundary between "the caller's error" and "our error" is the resolution step, not // the exception type: a FormatException thrown while binding a guid route param is a 400, // the same exception thrown inside the action is a 500. Resolution needs nothing from the // controller instance, so it runs first under its own catch. object?[] parameters; try { parameters = ResolveHttpParameters(action.Method, exchange, routeParams); } catch (Exception ex) when (ex is not OperationCanceledException) { WriteError(exchange, 400, ControllerErrorReporting.BadRequestCode, ControllerErrorReporting.ReportBadRequest(_logger, ex, exchange, $"{method} {path}")); return; } try { var controller = (RedbController)Activator.CreateInstance(action.ControllerType)!; controller.Context = _context; controller.Exchange = exchange; // The action's own exception, one TargetInvocationException removed (see ActionInvoker). var result = await ActionInvoker.InvokeAsync(action.Method, controller, parameters); WriteResult(exchange, result); } catch (Exception ex) { WriteError(exchange, 500, ControllerErrorReporting.ErrorCode, ControllerErrorReporting.Report(_logger, ex, exchange, $"{method} {path}")); } } /// /// Resolves parameters using HTTP-native headers: /// route params from registry + redbHttp.RouteParam.*, query from redbHttp.QueryParam.*, /// body from byte[] (HTTP consumer stores raw bytes). /// private object?[] ResolveHttpParameters( MethodInfo method, IExchange exchange, IReadOnlyDictionary routeParams) { var parameters = method.GetParameters(); var values = new object?[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { values[i] = ResolveHttpParameter(parameters[i], exchange, routeParams); } return values; } private object? ResolveHttpParameter( ParameterInfo param, IExchange exchange, IReadOnlyDictionary routeParams) { if (param.ParameterType == typeof(CancellationToken)) return CancellationToken.None; // [FromBody] if (param.GetCustomAttribute() is not null) return ResolveFromBody(exchange, param.ParameterType); // [FromHeader("name")] if (param.GetCustomAttribute() is { } headerAttr) { var raw = exchange.In.getHeader(headerAttr.Name); if (raw is not null) return ParameterResolver.ConvertValue(raw, param.ParameterType, headerAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ParameterResolver.ConvertValue(null, param.ParameterType); } // [FromProperty("name")] if (param.GetCustomAttribute() is { } propAttr) { var raw = exchange.getProperty(propAttr.Name); if (raw is not null) return ParameterResolver.ConvertValue(raw, param.ParameterType, propAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ParameterResolver.ConvertValue(null, param.ParameterType); } // [FromQuery("name")] — reads from redbHttp.QueryParam.{name} if (param.GetCustomAttribute() is { } queryAttr) { var raw = exchange.In.getHeader($"{QueryParamPrefix}{queryAttr.Name}"); if (raw is not null) return ParameterResolver.ConvertValue(raw, param.ParameterType, queryAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ParameterResolver.ConvertValue(null, param.ParameterType); } // [FromRoute("name")] — reads from route params extracted by template matching if (param.GetCustomAttribute() is { } routeAttr) { routeParams.TryGetValue(routeAttr.Name, out var routeValue); if (routeValue is not null) return ParameterResolver.ConvertValue(routeValue, param.ParameterType, routeAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ParameterResolver.ConvertValue(null, param.ParameterType); } // No attribute — try route params by name, then body for complex types if (routeParams.TryGetValue(param.Name!, out var implicitRouteValue)) return ParameterResolver.ConvertValue(implicitRouteValue, param.ParameterType, param.Name); if (!IsSimpleType(param.ParameterType)) return ResolveFromBody(exchange, param.ParameterType); return param.HasDefaultValue ? param.DefaultValue : null; } /// /// Deserializes the body from the exchange. HTTP consumer stores body as byte[], /// so we handle JSON deserialization from bytes, string, or typed object. /// private object? ResolveFromBody(IExchange exchange, Type targetType) { var body = exchange.In.Body; if (body is null) return null; if (targetType.IsInstanceOfType(body)) return body; // HTTP consumer stores body as byte[] — deserialize JSON from bytes if (body is byte[] bytes) { if (bytes.Length == 0) return null; if (targetType == typeof(byte[])) return bytes; if (targetType == typeof(string)) return System.Text.Encoding.UTF8.GetString(bytes); return JsonSerializer.Deserialize(bytes, targetType, _jsonOptions); } if (body is string json) return JsonSerializer.Deserialize(json, targetType, _jsonOptions); if (body is JsonElement element) return element.Deserialize(targetType, _jsonOptions); return ParameterResolver.ConvertValue(body, targetType); } private static void MergeHttpRouteParams(IExchange exchange, Dictionary routeParams) { foreach (var header in exchange.In.Headers) { if (header.Key.StartsWith(RouteParamPrefix, StringComparison.Ordinal) && header.Value is not null) { var paramName = header.Key[RouteParamPrefix.Length..]; routeParams.TryAdd(paramName, header.Value.ToString()!); } } } // HTTP response code header read by HttpConsumer (string constant to avoid dependency on redb.Route.Http) internal const string HttpResponseCodeHeader = "redbHttp.ResponseCode"; private void WriteResult(IExchange exchange, object? result) { // An Out that already exists was written by the action (or a step before the dispatcher): that is the reply. // Only a clone the dispatcher makes here carries the request body, and only that one is cleared below. var createdHere = exchange.Out is null; exchange.Out ??= exchange.In.Clone(); var defaultCode = result is null ? 204 : 200; if (result is not null) { // Serialize to JSON bytes for HTTP transport (consumer writes byte[] directly) if (result is not byte[] and not string) result = JsonSerializer.SerializeToUtf8Bytes(result, _jsonOptions); exchange.Out.Body = result; } else if (createdHere) { // No response body (controller returned null → 204 No Content). The // `exchange.Out ??= exchange.In.Clone()` above carries In.Body into Out, // which for HTTP requests with Content-Length: 0 is `Array.Empty()` // (non-null byte[]). Without clearing it here the downstream HTTP consumer // sees `body is byte[]` and calls Response.Body.WriteAsync(...), and Kestrel // hard-throws on 204 per RFC 7230 §3.3.3 / RFC 9112 §6.1 // ("Writing to the response body is invalid for responses with status code 204" // from HttpProtocol.FirstWriteAsyncInternal, even for zero-length writes). // The request body was input; it must not echo into the response. exchange.Out.Body = null; } // Respect response meta already set by the controller (e.g. via facade Forward // that propagated an inner OnException 5xx). Dispatcher only fills in defaults. if (!exchange.Out.Headers.ContainsKey("status.code")) exchange.Out.setHeader("status.code", defaultCode); // The consumer reads redbHttp.ResponseCode first: mirror the status that won above, so an action that set only // status.code (404 with its own body) is not answered as a 204. if (!exchange.Out.Headers.ContainsKey(HttpResponseCodeHeader)) exchange.Out.setHeader(HttpResponseCodeHeader, exchange.Out.GetHeader("status.code")); if (result is not null && !exchange.Out.Headers.ContainsKey("Content-Type")) exchange.Out.setHeader("Content-Type", "application/json"); } private void WriteError(IExchange exchange, int statusCode, string error, string message) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes( new ControllerErrorResponse { Error = error, Message = message, StatusCode = statusCode }, _jsonOptions); // Errors are authoritative: overwrite whatever a controller may have set before throwing. exchange.Out.setHeader("status.code", statusCode); exchange.Out.setHeader(HttpResponseCodeHeader, statusCode); exchange.Out.setHeader("Content-Type", "application/json"); } private static bool IsSimpleType(Type type) { var t = Nullable.GetUnderlyingType(type) ?? type; return t.IsPrimitive || t == typeof(string) || t == typeof(decimal) || t == typeof(DateTime) || t == typeof(DateTimeOffset) || t == typeof(Guid) || t.IsEnum; } }