Bundle: redb-route / redb.Route.Controllers (redb.Route.Controllers.txt), 19 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.Controllers/ActionInvoker.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/ActionInvoker.cs ---- using System.Reflection; using System.Runtime.ExceptionServices; namespace redb.Route.Controllers; /// /// Invokes a controller action and turns what it returned into the value the reply carries. Every dispatcher and /// the direct-invoke DSL overloads go through here, so an action behaves the same behind every transport. /// internal static class ActionInvoker { /// /// Calls on , awaits it when it is asynchronous, and /// returns its result: null for void, and . /// /// The shape is read from the method's DECLARED return type, as ASP.NET Core's ObjectMethodExecutor /// does. The run-time type cannot tell: an async Task method returns a Task<VoidTaskResult>, /// whose runtime-internal result then reached the reply as a body; and a is a /// struct that is not a at all, so it reached the reply unawaited. /// /// /// An exception the action throws synchronously arrives wrapped in by /// ; exactly that one wrapper is removed and the action's own /// exception is rethrown with its stack trace. An asynchronous action's exception comes out of the awaited /// task as it is. Nothing below that level is unwrapped. /// /// internal static async Task InvokeAsync(MethodInfo method, object controller, object?[] arguments) { object? returned; try { returned = method.Invoke(controller, arguments); } catch (TargetInvocationException tie) when (tie.InnerException is not null) { ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); throw; // unreachable: Throw() never returns } var declared = method.ReturnType; if (declared == typeof(Task)) { await ((Task)returned!).ConfigureAwait(false); return null; } if (declared == typeof(ValueTask)) { await ((ValueTask)returned!).ConfigureAwait(false); return null; } if (declared.IsGenericType) { var definition = declared.GetGenericTypeDefinition(); if (definition == typeof(Task<>)) { var task = (Task)returned!; await task.ConfigureAwait(false); return declared.GetProperty(nameof(Task.Result))!.GetValue(task); } if (definition == typeof(ValueTask<>)) { var task = (Task)declared.GetMethod(nameof(ValueTask.AsTask))!.Invoke(returned, null)!; await task.ConfigureAwait(false); return typeof(Task<>).MakeGenericType(declared.GetGenericArguments()) .GetProperty(nameof(Task.Result))!.GetValue(task); } } return returned; } } Path: redb-route/redb.Route.Controllers/Attributes/BindingAttributes.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/Attributes/BindingAttributes.cs ---- namespace redb.Route.Controllers.Attributes; /// Binds a parameter from the exchange message body (exchange.In.Body). JSON-deserialized. [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public sealed class FromBodyAttribute : Attribute { } /// Binds a parameter from a message header (exchange.In.Headers[name]). [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public sealed class FromHeaderAttribute : Attribute { /// Header key name. public string Name { get; } /// Header key name. public FromHeaderAttribute(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } } /// Binds a parameter from an exchange property (exchange.Properties[name]). [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public sealed class FromPropertyAttribute : Attribute { /// Property key name. public string Name { get; } /// Property key name. public FromPropertyAttribute(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } } /// Binds a parameter from a query string value (exchange.In.Headers["query.{name}"]). [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public sealed class FromQueryAttribute : Attribute { /// Query parameter name. public string Name { get; } /// Query parameter name. public FromQueryAttribute(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } } /// Binds a parameter from a route path segment (extracted from template matching, e.g. {id}). [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public sealed class FromRouteAttribute : Attribute { /// Route parameter name (must match a {param} in the route template). public string Name { get; } /// Route parameter name. public FromRouteAttribute(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } } Path: redb-route/redb.Route.Controllers/Attributes/GrpcMethodAttribute.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/Attributes/GrpcMethodAttribute.cs ---- namespace redb.Route.Controllers.Attributes; /// /// Maps a controller method to the name gRPC callers dispatch on (dispatch-method). Optional: /// without it the C# method name is the wire name, which means renaming the method breaks every client. /// A gRPC facade publishes its contract outside the codebase, so pin the name here and refactor freely. /// Mirrors , which does the same for SOAP operations. /// /// [GrpcMethod("ListUsers")] /// public Task<UserPage> List(int page) => ...; /// /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class GrpcMethodAttribute : Attribute { /// The gRPC dispatch name. public GrpcMethodAttribute(string method) => Method = method; /// The gRPC dispatch name. public string Method { get; } } Path: redb-route/redb.Route.Controllers/Attributes/HttpMethodAttributes.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/Attributes/HttpMethodAttributes.cs ---- namespace redb.Route.Controllers.Attributes; /// HTTP method type for route matching. public enum HttpMethodType { /// GET request. Get, /// POST request. Post, /// PUT request. Put, /// DELETE request. Delete, /// PATCH request. Patch } /// /// Base attribute for HTTP method markers on controller actions. /// These are route-table markers, not transport directives. /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public abstract class HttpMethodAttribute : Attribute { /// HTTP method this action responds to. public HttpMethodType Method { get; } /// Optional sub-template (e.g. "{id}"). public string? Template { get; } /// HTTP method type. /// Optional sub-template appended to the controller route. protected HttpMethodAttribute(HttpMethodType method, string? template = null) { Method = method; Template = template; } } /// Marks a controller action as handling GET requests. public sealed class HttpGetAttribute : HttpMethodAttribute { /// Optional sub-template (e.g. "{id}"). public HttpGetAttribute(string? template = null) : base(HttpMethodType.Get, template) { } } /// Marks a controller action as handling POST requests. public sealed class HttpPostAttribute : HttpMethodAttribute { /// Optional sub-template (e.g. "search"). public HttpPostAttribute(string? template = null) : base(HttpMethodType.Post, template) { } } /// Marks a controller action as handling PUT requests. public sealed class HttpPutAttribute : HttpMethodAttribute { /// Optional sub-template (e.g. "{id}"). public HttpPutAttribute(string? template = null) : base(HttpMethodType.Put, template) { } } /// Marks a controller action as handling DELETE requests. public sealed class HttpDeleteAttribute : HttpMethodAttribute { /// Optional sub-template (e.g. "{id}"). public HttpDeleteAttribute(string? template = null) : base(HttpMethodType.Delete, template) { } } /// Marks a controller action as handling PATCH requests. public sealed class HttpPatchAttribute : HttpMethodAttribute { /// Optional sub-template (e.g. "{id}"). public HttpPatchAttribute(string? template = null) : base(HttpMethodType.Patch, template) { } } Path: redb-route/redb.Route.Controllers/Attributes/RouteAttribute.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/Attributes/RouteAttribute.cs ---- namespace redb.Route.Controllers.Attributes; /// /// Specifies the base route path for a controller. /// Applied to classes inheriting . /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class RouteAttribute : Attribute { /// Route path template (e.g. "modules", "contexts"). public string Template { get; } /// Route path template. public RouteAttribute(string template) { Template = template ?? throw new ArgumentNullException(nameof(template)); } } Path: redb-route/redb.Route.Controllers/Attributes/SoapOperationAttribute.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/Attributes/SoapOperationAttribute.cs ---- namespace redb.Route.Controllers.Attributes; /// /// Maps a controller method to a SOAP operation — the local name of the <soap:Body> root element /// the SOAP consumer surfaces on redbSoap.operation. Optional: without it the method name is the /// operation. Use it when the request element name differs from the method name. /// /// [SoapOperation("GetFares")] /// public Task<GetFaresResponse> Fares([FromBody] GetFaresRequest req) => ...; /// /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class SoapOperationAttribute : Attribute { /// The SOAP operation name (the request Body element's local name). public SoapOperationAttribute(string operation) => Operation = operation; /// The SOAP operation name. public string Operation { get; } } Path: redb-route/redb.Route.Controllers/ControllerDispatcherProcessor.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/ControllerDispatcherProcessor.cs ---- using System.Reflection; using System.Text.Encodings.Web; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Controllers.Attributes; namespace redb.Route.Controllers; /// /// Standard error response model for controller dispatch failures. /// public sealed class ControllerErrorResponse { /// Error code or type. public string Error { get; init; } = "InternalError"; /// Human-readable error message. public string Message { get; init; } = string.Empty; /// HTTP-style status code. public int StatusCode { get; init; } = 500; } /// /// IProcessor that dispatches exchanges to actions. /// Reads route.path and route.method from exchange headers, matches against , /// resolves parameters, invokes the action, and writes the result to exchange.Out. /// public sealed class ControllerDispatcherProcessor : IProcessor { private readonly ControllerRegistry _registry; private readonly IRouteContext _context; private readonly IReadOnlyList _filters; private readonly ILogger? _logger; private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, // Emit non-ASCII (Cyrillic, emoji, diacritics) and ASCII punctuation like '"' // as-is in UTF-8 instead of escaping to \uXXXX. Safe for HTTP API responses; // only unsafe when embedding JSON inside HTML/JS, which dispatcher output never does. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; /// Header key for the request path (e.g. "modules/123"). public const string PathHeader = "route.path"; /// Header key for the HTTP method (e.g. "GET", "POST"). public const string MethodHeader = "route.method"; /// Controller registry with registered actions. /// Route context for controller instantiation. /// /// Optional cross-cutting filters applied around every action invocation. /// Sorted ascending by at construction. /// public ControllerDispatcherProcessor( ControllerRegistry registry, IRouteContext context, IEnumerable? filters = null) { _registry = registry ?? throw new ArgumentNullException(nameof(registry)); _context = context ?? throw new ArgumentNullException(nameof(context)); _filters = (filters ?? Array.Empty()) .OrderBy(f => f.Order) .ToArray(); _logger = ControllerErrorReporting.CreateLogger(context); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var path = exchange.In.GetHeader(PathHeader); var method = exchange.In.GetHeader(MethodHeader); if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(method)) { WriteError(exchange, 400, "BadRequest", $"Missing required headers: {PathHeader} and/or {MethodHeader}"); return; } var action = _registry.Resolve(method, path, out var routeParams); if (action is null) { WriteError(exchange, 404, "NotFound", $"No action matches {method} {path}"); return; } var filterContext = _filters.Count > 0 ? new ControllerActionContext(exchange, action, routeParams) : null; // BeforeAsync filters: ascending order. Errors are isolated per-filter. if (filterContext is not null) { for (var i = 0; i < _filters.Count; i++) { try { await _filters[i].BeforeAsync(filterContext, ct); } catch (Exception ex) { LogFilterFailure(ex, _filters[i], nameof(IControllerActionFilter.BeforeAsync)); } } } var sw = filterContext is not null ? System.Diagnostics.Stopwatch.StartNew() : null; try { // The boundary between "the caller's error" and "our error" is the resolution step, as on the HTTP, // SignalR and gRPC dispatchers: a FormatException while binding a route or query value is a 400, the // same exception inside the action is a 500. The filters' AfterAsync still runs (finally below). object?[] parameters; try { parameters = ParameterResolver.ResolveParameters(action.Method, exchange, routeParams); } catch (Exception ex) when (ex is not OperationCanceledException) { if (filterContext is not null) filterContext.Exception = ex; WriteError(exchange, 400, ControllerErrorReporting.BadRequestCode, ControllerErrorReporting.ReportBadRequest(_logger, ex, exchange, $"{method} {path}")); return; } if (filterContext is not null) filterContext.Arguments = parameters; 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); if (filterContext is not null) filterContext.Result = result; WriteResult(exchange, result); } catch (Exception ex) { if (filterContext is not null) filterContext.Exception = ex; WriteUnhandled(exchange, ex, path, method); } finally { if (filterContext is not null) { sw!.Stop(); filterContext.Elapsed = sw.Elapsed; filterContext.StatusCode = exchange.Out?.GetHeader("status.code") ?? 0; // AfterAsync filters: reverse order. Errors are isolated per-filter. for (var i = _filters.Count - 1; i >= 0; i--) { try { await _filters[i].AfterAsync(filterContext, ct); } catch (Exception ex) { LogFilterFailure(ex, _filters[i], nameof(IControllerActionFilter.AfterAsync)); } } } } } private static 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) { exchange.Out.Body = result; } else if (createdHere) { // No result, no body: our own clone of the request is not the reply. exchange.Out.Body = null; } // Respect meta already set by the controller (e.g. facade Forward propagating an // inner OnException 5xx). Dispatcher only fills in defaults. if (!exchange.Out.Headers.ContainsKey("status.code")) exchange.Out.setHeader("status.code", defaultCode); if (result is not null && !exchange.Out.Headers.ContainsKey("Content-Type")) exchange.Out.setHeader("Content-Type", "application/json"); } /// /// A filter threw. It never breaks dispatch, but it is logged: /// documents exactly that, and a swallowed throw made an audit filter that fails on every request /// indistinguishable from one that works. /// private void LogFilterFailure(Exception exception, IControllerActionFilter filter, string stage) => _logger?.LogError(exception, "Controller action filter {Filter} threw in {Stage}; dispatch continues", filter.GetType().FullName, stage); /// An action failed: generic message out, the exception to the log (see ). private void WriteUnhandled(IExchange exchange, Exception exception, string? path, string? method) => WriteError(exchange, 500, ControllerErrorReporting.ErrorCode, ControllerErrorReporting.Report(_logger, exception, exchange, $"{method} {path}")); private static void WriteError(IExchange exchange, int statusCode, string error, string message) { var errorResponse = new ControllerErrorResponse { Error = error, Message = message, StatusCode = statusCode }; exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = errorResponse; // Errors are authoritative: overwrite whatever a controller may have set before throwing. exchange.Out.setHeader("status.code", statusCode); exchange.Out.setHeader("Content-Type", "application/json"); } } Path: redb-route/redb.Route.Controllers/ControllerErrorReporting.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/ControllerErrorReporting.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Controllers; /// /// What a caller is told when an action fails for a reason the framework does not model, and where the /// real reason goes instead. One place for all five dispatchers: each of them used to carry its own /// copy of "put the exception's Message in the response", and a copy is exactly how one of them /// stays wrong after the others are fixed. /// /// The exception's text is written by whoever threw it and routinely carries internal detail — a file /// path, a connection string, the name of an inner service. Handing that to a caller is a disclosure. /// The caller gets a generic sentence /// and the exchange id to quote; the exception goes to the log under the same id, so an operator can /// still find out what actually happened. Errors the framework itself produces (400 for a missing /// header, 404 for no matching action) keep their text: it is ours and says nothing private. /// /// internal static class ControllerErrorReporting { /// Error code reported for any unhandled action failure. public const string ErrorCode = "InternalError"; /// Error code reported when the request could not be bound to the action's parameters. public const string BadRequestCode = "BadRequest"; /// /// Logs a request-binding failure and returns the message the caller should see. /// /// /// A body that does not bind is the CALLER's error: an expected event class, logged as a /// Warning without a stack — junk POSTed from outside must not fill the operator's log with /// error stacks (that is also a nudge-the-server-with-garbage log-flooding vector). And unlike /// action failures, the exception text here describes the caller's own bytes (the missing /// member, the unparsable token), so returning it is the BR-4 rule, not a violation of it. /// public static string ReportBadRequest(ILogger? logger, Exception exception, IExchange exchange, string? operation) { logger?.LogWarning( "Malformed request for {Operation} (exchange {ExchangeId}): {Reason}", operation, exchange.ExchangeId, exception.Message); return exception.Message; } /// /// The dispatcher's logger. Looks in the context's own service table first and then in the DI /// container: IRouteContext.GetService<T>() reads only the table, and a host that builds /// the context as new RouteContext(serviceProvider) after AddLogging() never puts the /// factory there. Missing that second step is how withholding the exception from the caller turns /// into losing it altogether — worse for the operator than the disclosure it replaced. /// public static ILogger? CreateLogger(IRouteContext context) { var factory = context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(ILoggerFactory)) as ILoggerFactory; return factory?.CreateLogger(); } /// /// Logs against the exchange and returns the message the caller may /// see. Without a logger the detail is lost — that is the host's choice of configuration, and it is /// still better than disclosing it. /// /// Dispatcher logger, or null when the context has no logger factory. /// The exception as thrown by the action (already unwrapped from any TargetInvocationException). /// The exchange being dispatched; its id is the reference given to the caller. /// What was being dispatched, for the log line (e.g. "GET modules/42"). public static string Report(ILogger? logger, Exception exception, IExchange exchange, string? operation) { logger?.LogError(exception, "Unhandled exception in controller action for {Operation} (exchange {ExchangeId})", operation, exchange.ExchangeId); return $"An unexpected error occurred while processing the request (ref: {exchange.ExchangeId})."; } } Path: redb-route/redb.Route.Controllers/ControllerRegistry.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/ControllerRegistry.cs ---- using System.Collections.Concurrent; using System.Reflection; using System.Text.RegularExpressions; using redb.Route.Controllers.Attributes; namespace redb.Route.Controllers; /// /// Route table entry holding controller type, method info, and compiled template segments. /// public sealed record ControllerAction( Type ControllerType, MethodInfo Method, HttpMethodType HttpMethod, string Template, string[] Segments); /// /// Scans assemblies for subclasses, builds a route lookup table, /// and resolves incoming (method, path) pairs to controller actions. /// Thread-safe. Lookup is O(n) on segments but typically fast given small route counts. /// public sealed class ControllerRegistry { private readonly ConcurrentBag _actions = new(); private static readonly Regex TemplateParamRegex = new(@"\{(\w+)\}", RegexOptions.Compiled); /// Returns all registered controller actions. public IReadOnlyCollection Actions => _actions.ToArray(); /// /// Scans an assembly for all non-abstract subclasses /// and registers their attributed actions. /// /// Assembly to scan. /// Number of actions registered from this assembly. public int RegisterAssembly(Assembly assembly) { ArgumentNullException.ThrowIfNull(assembly); var count = 0; foreach (var type in assembly.GetTypes()) { if (type.IsAbstract || !type.IsSubclassOf(typeof(RedbController))) continue; count += RegisterController(type); } return count; } /// /// Registers a single controller type and its attributed actions. /// /// Controller type to register. /// Number of actions registered. public int RegisterController(Type controllerType) { ArgumentNullException.ThrowIfNull(controllerType); var routeAttr = controllerType.GetCustomAttribute(); var basePath = routeAttr?.Template ?? controllerType.Name.Replace("Controller", "").ToLowerInvariant(); var count = 0; foreach (var method in controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var httpAttr = method.GetCustomAttribute(); if (httpAttr is null) continue; var template = string.IsNullOrEmpty(httpAttr.Template) ? basePath : $"{basePath}/{httpAttr.Template}"; var segments = template.Split('/', StringSplitOptions.RemoveEmptyEntries); _actions.Add(new ControllerAction(controllerType, method, httpAttr.Method, template, segments)); count++; } return count; } /// /// Matches an incoming request path and HTTP method against the route table. /// Extracts path parameters from template placeholders. /// /// HTTP method (GET, POST, etc.). /// Request path (e.g. "modules/123"). /// Extracted route parameters (e.g. {id} → "123"). /// Matched action or null if no match. public ControllerAction? Resolve(HttpMethodType httpMethod, string path, out Dictionary routeParams) { routeParams = new Dictionary(StringComparer.OrdinalIgnoreCase); var pathSegments = path.Split('/', StringSplitOptions.RemoveEmptyEntries); // Collect all matches, then pick the most specific. Specificity = fewer // placeholder segments (literals win over {param}) so that e.g. // DELETE /me/sessions/current // wins over // DELETE /me/sessions/{sessionId} // The underlying store is a ConcurrentBag whose enumeration order is undefined, // so without this explicit ranking collisions would be non-deterministic. ControllerAction? best = null; Dictionary? bestParams = null; var bestPlaceholderCount = int.MaxValue; foreach (var action in _actions) { if (action.HttpMethod != httpMethod) continue; if (action.Segments.Length != pathSegments.Length) continue; var matched = true; var placeholderCount = 0; var candidateParams = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var i = 0; i < action.Segments.Length; i++) { var seg = action.Segments[i]; var match = TemplateParamRegex.Match(seg); if (match.Success && match.Value == seg) { // Entire segment is a parameter placeholder candidateParams[match.Groups[1].Value] = pathSegments[i]; placeholderCount++; } else if (!seg.Equals(pathSegments[i], StringComparison.OrdinalIgnoreCase)) { matched = false; break; } } if (matched && placeholderCount < bestPlaceholderCount) { best = action; bestParams = candidateParams; bestPlaceholderCount = placeholderCount; if (placeholderCount == 0) break; // exact literal match — cannot be beaten } } if (best is not null) { routeParams = bestParams!; return best; } return null; } /// /// Resolves using string method name (case-insensitive) instead of enum. /// Parses "GET", "POST", etc. to . /// public ControllerAction? Resolve(string httpMethod, string path, out Dictionary routeParams) { if (!Enum.TryParse(httpMethod, ignoreCase: true, out var method)) { routeParams = new Dictionary(); return null; } return Resolve(method, path, out routeParams); } } Path: redb-route/redb.Route.Controllers/Extensions/ControllerRouteExtensions.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/Extensions/ControllerRouteExtensions.cs ---- using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; namespace redb.Route.Controllers.Extensions; /// /// DSL extension methods for dispatching exchanges to actions. /// Provides five overloads of .RedbController() on . /// public static class ControllerRouteExtensions { /// /// Dispatches to a controller action resolved from exchange headers (route.path, route.method). /// Full auto-dispatch: the dispatcher reads headers and matches against the registry. /// /// Route definition. /// Controller registry with registered actions. public static IRouteDefinition RedbController(this IRouteDefinition route, ControllerRegistry registry) { ArgumentNullException.ThrowIfNull(registry); return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new ControllerDispatcherProcessor(registry, context); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches to a specific controller type. Method is resolved from exchange header (route.method) /// and path from (route.path), but only actions on are considered. /// /// Controller type to dispatch to. /// Route definition. public static IRouteDefinition RedbController(this IRouteDefinition route) where TController : RedbController { var registry = new ControllerRegistry(); registry.RegisterController(typeof(TController)); return route.RedbController(registry); } /// /// Dispatches to a specific method on a specific controller type. /// Ignores route.method and route.path headers — directly invokes the named method. /// /// Controller type. /// Route definition. /// Name of the method to invoke. public static IRouteDefinition RedbController(this IRouteDefinition route, string methodName) where TController : RedbController { ArgumentNullException.ThrowIfNull(methodName); return route.Process(async (exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var method = typeof(TController).GetMethod(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); if (method is null) throw new InvalidOperationException($"Method '{methodName}' not found on {typeof(TController).Name}"); var controller = (RedbController)Activator.CreateInstance(typeof(TController))!; controller.Context = context; controller.Exchange = exchange; var parameters = ParameterResolver.ResolveParameters(method, exchange, new Dictionary()); var result = await ActionInvoker.InvokeAsync(method, controller, parameters); if (result is not null) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = result; exchange.Out.setHeader("status.code", 200); } }); } /// /// Dispatches to a controller and method by string names. /// Resolves the controller type from the registry, then invokes the named method. /// /// Route definition. /// Controller registry. /// Controller name (without "Controller" suffix). /// Method name to invoke. public static IRouteDefinition RedbController( this IRouteDefinition route, ControllerRegistry registry, string controllerName, string methodName) { ArgumentNullException.ThrowIfNull(registry); ArgumentNullException.ThrowIfNull(controllerName); ArgumentNullException.ThrowIfNull(methodName); return route.Process(async (exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var action = registry.Actions.FirstOrDefault(a => a.ControllerType.Name.Replace("Controller", "") .Equals(controllerName, StringComparison.OrdinalIgnoreCase) && a.Method.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase)); if (action is null) throw new InvalidOperationException( $"No action found for controller '{controllerName}', method '{methodName}'"); var controller = (RedbController)Activator.CreateInstance(action.ControllerType)!; controller.Context = context; controller.Exchange = exchange; var parameters = ParameterResolver.ResolveParameters(action.Method, exchange, new Dictionary()); var result = await ActionInvoker.InvokeAsync(action.Method, controller, parameters); if (result is not null) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = result; exchange.Out.setHeader("status.code", 200); } }); } /// /// Dispatches to a controller action using dynamic expressions for controller and method selection. /// The expressions are evaluated at runtime from exchange data. /// /// Route definition. /// Controller registry. /// Expression returning controller name from exchange. /// Expression returning method name from exchange. public static IRouteDefinition RedbController( this IRouteDefinition route, ControllerRegistry registry, Func controllerExpr, Func methodExpr) { ArgumentNullException.ThrowIfNull(registry); ArgumentNullException.ThrowIfNull(controllerExpr); ArgumentNullException.ThrowIfNull(methodExpr); return route.Process(async (exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var controllerName = controllerExpr(exchange); var methodName = methodExpr(exchange); var action = registry.Actions.FirstOrDefault(a => a.ControllerType.Name.Replace("Controller", "") .Equals(controllerName, StringComparison.OrdinalIgnoreCase) && a.Method.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase)); if (action is null) throw new InvalidOperationException( $"No action found for controller '{controllerName}', method '{methodName}'"); var controller = (RedbController)Activator.CreateInstance(action.ControllerType)!; controller.Context = context; controller.Exchange = exchange; var parameters = ParameterResolver.ResolveParameters(action.Method, exchange, new Dictionary()); var result = await ActionInvoker.InvokeAsync(action.Method, controller, parameters); if (result is not null) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = result; exchange.Out.setHeader("status.code", 200); } }); } // ── SignalR controller dispatch ──────────────────────── /// /// Dispatches SignalR hub invocations to methods on . /// Method name is read from redbSignalR.Method header; arguments are resolved /// positionally from the exchange body. /// No HTTP attributes required — all public instance methods are exposed. /// /// Controller type whose methods become callable hub methods. /// Route definition. public static IRouteDefinition RedbSignalRController(this IRouteDefinition route) where TController : RedbController { return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new SignalRControllerDispatcher(context, typeof(TController)); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches SignalR hub invocations to methods across multiple controller types. /// Method name is read from redbSignalR.Method header. Use qualified format /// "Controller.Method" (e.g. "Modules.GetAll") to disambiguate. /// Unqualified names resolve to first match. /// /// Route definition. /// Controller types to register. public static IRouteDefinition RedbSignalRController( this IRouteDefinition route, params Type[] controllerTypes) { return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new SignalRControllerDispatcher(context, controllerTypes); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches SignalR hub invocations to controllers registered in an existing /// . Reuses the registry as a source of controller types; /// dispatch is by method name (not by HTTP method/path template). /// /// Route definition. /// Controller registry with registered controllers. public static IRouteDefinition RedbSignalRController( this IRouteDefinition route, ControllerRegistry registry) { ArgumentNullException.ThrowIfNull(registry); var types = registry.Actions.Select(a => a.ControllerType).Distinct().ToArray(); return route.RedbSignalRController(types); } // ── SOAP controller dispatch ────────────────────────── /// /// Dispatches SOAP requests to methods on by operation. The operation is /// read from redbSoap.operation (set by the SOAP consumer); the XML body binds to the method's /// [FromBody] / single complex parameter, and the return value is XML-serialized into the response. /// No HTTP attributes required. Use when the method /// name differs from the operation. /// /// Controller whose methods become SOAP operations. /// Route definition (behind a Soap.Listen(...) consumer). public static IRouteDefinition RedbSoapController(this IRouteDefinition route) where TController : RedbController { return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new SoapControllerDispatcher(context, typeof(TController)); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches SOAP requests across multiple controller types by operation (redbSoap.operation). Use /// the qualified form "Controller.Operation" to disambiguate; unqualified names resolve to the first /// match. /// /// Route definition. /// Controller types to register. public static IRouteDefinition RedbSoapController( this IRouteDefinition route, params Type[] controllerTypes) { return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new SoapControllerDispatcher(context, controllerTypes); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches SOAP requests to controllers registered in an existing , /// reusing it as a source of controller types; dispatch is by SOAP operation, not HTTP method/path. /// /// Route definition. /// Controller registry with registered controllers. public static IRouteDefinition RedbSoapController( this IRouteDefinition route, ControllerRegistry registry) { ArgumentNullException.ThrowIfNull(registry); var types = registry.Actions.Select(a => a.ControllerType).Distinct().ToArray(); return route.RedbSoapController(types); } // ── HTTP controller dispatch ────────────────────────── /// /// Dispatches HTTP requests to controller actions using REST conventions. /// Reads redbHttp.Method and redbHttp.Path headers set by the HTTP consumer, /// resolves actions from the , and binds parameters from /// route templates (redbHttp.RouteParam.*), query strings (redbHttp.QueryParam.*), /// and request body (byte[]). /// This is the HTTP-native dispatch — no manual header translation needed. /// /// Route definition. /// Controller registry with registered actions. public static IRouteDefinition RedbHttpController(this IRouteDefinition route, ControllerRegistry registry) { ArgumentNullException.ThrowIfNull(registry); return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new HttpControllerDispatcher(registry, context); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches HTTP requests to a specific controller type using REST conventions. /// Reads redbHttp.Method and redbHttp.Path from the HTTP consumer. /// Only actions on are considered. /// /// Controller type to dispatch to. /// Route definition. public static IRouteDefinition RedbHttpController(this IRouteDefinition route) where TController : RedbController { var registry = new ControllerRegistry(); registry.RegisterController(typeof(TController)); return route.RedbHttpController(registry); } // ── gRPC controller dispatch ────────────────────────── /// /// Dispatches gRPC requests to methods on . /// Method name is read from dispatch-method header (flows through gRPC metadata /// unfiltered); body is deserialized from byte[] JSON for positional argument binding. /// No HTTP attributes required — all public instance methods are exposed. /// /// Controller type whose methods become callable via gRPC. /// Route definition. public static IRouteDefinition RedbGrpcController(this IRouteDefinition route) where TController : RedbController { return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new GrpcControllerDispatcher(context, typeof(TController)); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches gRPC requests to methods across multiple controller types. /// Method name is read from dispatch-method header. Use qualified format /// "Controller.Method" (e.g. "Modules.GetAll") to disambiguate. /// Unqualified names resolve to first match. /// /// Route definition. /// Controller types to register. public static IRouteDefinition RedbGrpcController( this IRouteDefinition route, params Type[] controllerTypes) { return route.Process((exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); var dispatcher = new GrpcControllerDispatcher(context, controllerTypes); return dispatcher.Process(exchange, ct); }); } /// /// Dispatches gRPC requests to controllers registered in an existing /// . Reuses the registry as a source of controller types; /// dispatch is by method name (not by HTTP method/path template). /// /// Route definition. /// Controller registry with registered controllers. public static IRouteDefinition RedbGrpcController( this IRouteDefinition route, ControllerRegistry registry) { ArgumentNullException.ThrowIfNull(registry); var types = registry.Actions.Select(a => a.ControllerType).Distinct().ToArray(); return route.RedbGrpcController(types); } } Path: redb-route/redb.Route.Controllers/GrpcControllerDispatcher.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/GrpcControllerDispatcher.cs ---- using System.Collections.Frozen; using System.Reflection; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Controllers; /// /// Dispatches gRPC requests to controller methods by method name. /// /// The method name is read from dispatch-method header (a regular header /// that flows through gRPC metadata without being filtered by producer/consumer). /// Body is treated as JSON — single value or array of positional arguments. /// /// /// Usage: the client (or middleware) sets exchange.In.Headers["dispatch-method"] = "MethodName" /// before sending via . Qualified names like /// "Controller.Method" are supported for multi-controller dispatch. /// /// public sealed class GrpcControllerDispatcher : IProcessor { private readonly FrozenDictionary _methods; private readonly IRouteContext _context; private readonly ILogger? _logger; /// Header key for the dispatch method name (flows through gRPC metadata unfiltered). internal const string MethodHeader = "dispatch-method"; private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; /// Route context for controller instantiation. /// One or more controller types to register. public GrpcControllerDispatcher(IRouteContext context, params Type[] controllerTypes) { _context = context ?? throw new ArgumentNullException(nameof(context)); if (controllerTypes is null || controllerTypes.Length == 0) throw new ArgumentException("At least one controller type is required.", nameof(controllerTypes)); _methods = BuildMethodMap(controllerTypes); _logger = ControllerErrorReporting.CreateLogger(context); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var methodName = exchange.In.GetHeader(MethodHeader); if (string.IsNullOrEmpty(methodName)) { WriteError(exchange, 400, "BadRequest", $"Missing required header: {MethodHeader}"); return; } if (!_methods.TryGetValue(methodName, out var entry)) { WriteError(exchange, 404, "NotFound", $"Method '{methodName}' not found on registered controllers"); return; } // Binding failures are the caller's 400, action failures are our 500 — the boundary is // the resolution step, same as the HTTP dispatcher. object?[] parameters; try { // gRPC body is byte[] — deserialize from JSON for positional binding var body = DeserializeBody(exchange.In.Body); parameters = ParameterResolver.ResolvePositional(entry.Method, body, ct); } catch (Exception ex) when (ex is not OperationCanceledException) { WriteError(exchange, 400, ControllerErrorReporting.BadRequestCode, ControllerErrorReporting.ReportBadRequest(_logger, ex, exchange, methodName)); return; } try { var controller = (RedbController)Activator.CreateInstance(entry.ControllerType)!; controller.Context = _context; controller.Exchange = exchange; // The action's own exception, one TargetInvocationException removed (see ActionInvoker). var result = await ActionInvoker.InvokeAsync(entry.Method, controller, parameters); WriteResult(exchange, result); } catch (Exception ex) { WriteError(exchange, 500, ControllerErrorReporting.ErrorCode, ControllerErrorReporting.Report(_logger, ex, exchange, methodName)); } } /// /// Deserializes gRPC body. The consumer stores body as byte[]. /// If the JSON is an array, unpacks to object[] for positional binding. /// private static object? DeserializeBody(object? body) { if (body is null) return null; if (body is byte[] bytes) { if (bytes.Length == 0) return null; var element = JsonSerializer.Deserialize(bytes, JsonOptions); return UnpackJsonElement(element); } // Already deserialized (e.g., in unit tests) return body; } private static object? UnpackJsonElement(JsonElement element) { if (element.ValueKind == JsonValueKind.Array) { var items = new object?[element.GetArrayLength()]; for (var i = 0; i < items.Length; i++) items[i] = element[i]; return items; } return element; } private static FrozenDictionary BuildMethodMap(Type[] controllerTypes) { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var type in controllerTypes) { if (!type.IsSubclassOf(typeof(RedbController))) throw new ArgumentException($"Type '{type.Name}' does not inherit from RedbController."); var controllerName = type.Name.EndsWith("Controller", StringComparison.Ordinal) ? type.Name[..^10] : type.Name; foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var entry = new MethodEntry(type, method); // [GrpcMethod] pins the wire name so renaming the C# method is not a breaking change for // callers. Same role SoapOperationAttribute plays for SOAP operations. var name = method.GetCustomAttribute()?.Method ?? method.Name; // Qualified name: "Modules.GetAll" — always registered, last-write wins per controller map[$"{controllerName}.{name}"] = entry; // Short name: "GetAll" — only if no collision across controllers map.TryAdd(name, entry); } } return map.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); } private static 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, // with its own body and status. Only a clone the dispatcher makes here carries the request body. var createdHere = exchange.Out is null; exchange.Out ??= exchange.In.Clone(); if (result is null) { if (createdHere) exchange.Out.Body = null; // our own clone of the request is not the reply if (!exchange.Out.Headers.ContainsKey("status.code")) exchange.Out.setHeader("status.code", 204); return; } // Serialize result to JSON bytes for gRPC response if (result is not byte[] and not string) result = JsonSerializer.SerializeToUtf8Bytes(result, JsonOptions); exchange.Out.Body = result; exchange.Out.setHeader("status.code", 200); } private static 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); exchange.Out.setHeader("status.code", statusCode); } internal sealed record MethodEntry(Type ControllerType, MethodInfo Method); } 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; } } Path: redb-route/redb.Route.Controllers/IControllerActionFilter.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/IControllerActionFilter.cs ---- using redb.Route.Abstractions; namespace redb.Route.Controllers; /// /// Per-action invocation context passed to s. /// All mutable fields are populated by /// before filters are invoked. /// public sealed class ControllerActionContext { /// The current message exchange. public IExchange Exchange { get; } /// Resolved controller action descriptor. public ControllerAction Action { get; } /// Route parameters extracted from the path. public IReadOnlyDictionary RouteParams { get; } /// Resolved positional argument values for the action method. public object?[] Arguments { get; internal set; } = Array.Empty(); /// Action result (set after invocation, before ). public object? Result { get; internal set; } /// Exception thrown by the action (if any). public Exception? Exception { get; internal set; } /// HTTP-style status code written to the response. public int StatusCode { get; internal set; } /// Wall-clock duration of the action invocation (excluding filter Before phase). public TimeSpan Elapsed { get; internal set; } /// Free-form items bag for filter-to-filter communication within a single invocation. public IDictionary Items { get; } = new Dictionary(StringComparer.Ordinal); public ControllerActionContext( IExchange exchange, ControllerAction action, IReadOnlyDictionary routeParams) { Exchange = exchange; Action = action; RouteParams = routeParams; } } /// /// Optional filter SPI invoked around every controller action by /// . Filters are resolved once at /// dispatcher construction time and ordered by ascending. /// /// runs in ascending order, /// runs in reverse (descending) order — classic onion model. /// /// /// Filters MUST be tolerant: throwing from a filter is logged but does not propagate /// to the action result. Use this for cross-cutting concerns like auditing, metrics, /// correlation IDs. /// /// public interface IControllerActionFilter { /// Lower values run first in , last in . int Order { get; } /// Invoked before the action method is called. Task BeforeAsync(ControllerActionContext context, CancellationToken ct); /// /// Invoked after the action method completes (whether success or failure). /// Inspect to detect failures. /// Task AfterAsync(ControllerActionContext context, CancellationToken ct); } Path: redb-route/redb.Route.Controllers/ParameterResolver.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/ParameterResolver.cs ---- using System.Globalization; using System.Reflection; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Controllers.Attributes; using redb.Route.Core; namespace redb.Route.Controllers; /// /// Resolves method parameters from based on binding attributes. /// Handles JSON deserialization for [FromBody], primitive conversion for others. /// public static class ParameterResolver { private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; /// /// Resolves all parameters for a controller method from the exchange and route params. /// /// Target method. /// Current exchange. /// Route path parameters extracted by template matching. /// Array of resolved parameter values. public static object?[] ResolveParameters( 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] = ResolveParameter(parameters[i], exchange, routeParams); } return values; } private static object? ResolveParameter( ParameterInfo param, IExchange exchange, IReadOnlyDictionary routeParams) { // CancellationToken — special case 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 ConvertValue(raw, param.ParameterType, headerAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ConvertValue(null, param.ParameterType); } // [FromProperty("name")] if (param.GetCustomAttribute() is { } propAttr) { var raw = exchange.getProperty(propAttr.Name); if (raw is not null) return ConvertValue(raw, param.ParameterType, propAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ConvertValue(null, param.ParameterType); } // [FromQuery("name")] if (param.GetCustomAttribute() is { } queryAttr) { var raw = exchange.In.getHeader($"query.{queryAttr.Name}"); if (raw is not null) return ConvertValue(raw, param.ParameterType, queryAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ConvertValue(null, param.ParameterType); } // [FromRoute("name")] if (param.GetCustomAttribute() is { } routeAttr) { routeParams.TryGetValue(routeAttr.Name, out var routeValue); if (routeValue is not null) return ConvertValue(routeValue, param.ParameterType, routeAttr.Name); return param.HasDefaultValue ? param.DefaultValue : ConvertValue(null, param.ParameterType); } // No attribute — try route params by parameter name, then body if (routeParams.TryGetValue(param.Name!, out var implicitRouteValue)) return ConvertValue(implicitRouteValue, param.ParameterType, param.Name); // Default: try to resolve from body if it's a complex type if (!IsSimpleType(param.ParameterType)) return ResolveFromBody(exchange, param.ParameterType); return param.HasDefaultValue ? param.DefaultValue : null; } private static 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 a string, try JSON deserialization if (body is string json) return JsonSerializer.Deserialize(json, targetType, JsonOptions); // If body is a JsonElement if (body is JsonElement element) return element.Deserialize(targetType, JsonOptions); return ConvertValue(body, targetType); } /// /// Converts a bound value to the parameter's type. A missing value (null) is the type's default; a value /// that is present but does not convert is an error, as Camel's ParameterBindingException: binding /// page=abc as 0 answers a question the caller never asked. The dispatchers report it as the /// caller's 400. /// /// The raw value (header, query, route, property or positional argument). /// The parameter type. /// Where the value came from, named in the error (header, query key, parameter). /// The value is present and does not convert to . internal static object? ConvertValue(object? value, Type targetType, string? parameterName = null) { if (value is null) return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; if (targetType.IsInstanceOfType(value)) return value; var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; try { if (value is string text) { if (underlying == typeof(Guid)) return Guid.Parse(text); // Not IConvertible, so Convert.ChangeType below could never produce it. if (underlying == typeof(DateTimeOffset)) return DateTimeOffset.Parse(text, CultureInfo.InvariantCulture); if (underlying.IsEnum) return Enum.Parse(underlying, text, ignoreCase: true); } // Header, query, route and property values are wire text: "12.5" is twelve and a half on every // server, not 125 under de-DE or a failed parse under ru-RU. return RouteDecimal.ChangeType(value, underlying, CultureInfo.InvariantCulture); } catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException or ArgumentException) { var subject = parameterName is null ? string.Empty : $"Parameter '{parameterName}': "; throw new FormatException($"{subject}'{value}' is not a valid {underlying.Name}.", ex); } } /// /// Resolves method parameters positionally from a SignalR-style body. /// Body is unpacked as: null → no args, single value → [value], object[] → positional. /// /// Target method. /// Exchange body (null, single value, or object[] from RedbBridgeHub). /// Cancellation token to inject for CancellationToken parameters. /// Array of resolved parameter values. internal static object?[] ResolvePositional(MethodInfo method, object? body, CancellationToken ct = default) { var allParams = method.GetParameters(); if (allParams.Length == 0) return []; // A JSON object binds BY NAME (honouring [FromRoute]/[FromQuery] key names, [FromBody] = the whole // object, a lone unbound complex parameter = the whole object). Arrays and everything else stay // positional, so existing single-value and positional-array callers are unchanged. if (body is JsonElement { ValueKind: JsonValueKind.Object } jsonObject) return ResolveNamed(allParams, jsonObject, ct); // Unpack body into args array var args = body switch { null => Array.Empty(), object[] arr => arr, _ => new[] { body } }; var values = new object?[allParams.Length]; var argIdx = 0; for (var i = 0; i < allParams.Length; i++) { var param = allParams[i]; if (param.ParameterType == typeof(CancellationToken)) { values[i] = ct; continue; } if (argIdx < args.Length) { values[i] = ConvertOrDeserialize(args[argIdx], param.ParameterType, param.Name); argIdx++; } else { values[i] = param.HasDefaultValue ? param.DefaultValue : null; } } return values; } /// /// Binds a JSON-object body by name. A [FromBody] parameter (or, when none is present, the single /// unbound complex parameter) receives the whole object; every other parameter takes the object property /// matching its name — or its [FromRoute] / [FromQuery] key — case-insensitively; unmatched /// parameters fall back to their default. is injected. Extra object keys /// are ignored by deserialization. /// private static object?[] ResolveNamed(ParameterInfo[] parameters, JsonElement obj, CancellationToken ct) { var hasFromBody = false; foreach (var p in parameters) if (p.GetCustomAttribute() is not null) { hasFromBody = true; break; } var values = new object?[parameters.Length]; var loneComplex = new List(); for (var i = 0; i < parameters.Length; i++) { var p = parameters[i]; if (p.ParameterType == typeof(CancellationToken)) { values[i] = ct; continue; } if (p.GetCustomAttribute() is not null) { values[i] = obj.Deserialize(p.ParameterType, JsonOptions); continue; } var key = p.GetCustomAttribute()?.Name ?? p.GetCustomAttribute()?.Name ?? p.Name!; if (TryGetPropertyIgnoreCase(obj, key, out var element)) { values[i] = ConvertOrDeserialize(element, p.ParameterType, key); continue; } // Unbound: take the default now; a lone complex parameter may receive the whole object below. values[i] = p.HasDefaultValue ? p.DefaultValue : ConvertValue(null, p.ParameterType); if (!hasFromBody && !IsSimpleType(p.ParameterType)) loneComplex.Add(i); } // No [FromBody], exactly one unbound complex parameter: it receives the whole object. This preserves // the common `Method(RequestDto dto)` shape whose parameter name never matches the object's keys. if (!hasFromBody && loneComplex.Count == 1) values[loneComplex[0]] = obj.Deserialize(parameters[loneComplex[0]].ParameterType, JsonOptions); return values; } private static bool TryGetPropertyIgnoreCase(JsonElement obj, string name, out JsonElement value) { foreach (var prop in obj.EnumerateObject()) if (string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase)) { value = prop.Value; return true; } value = default; return false; } /// /// Converts a single argument value to the target type, /// using JSON deserialization for complex types when needed. /// private static object? ConvertOrDeserialize(object? value, Type targetType, string? parameterName) { if (value is null) return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; if (targetType.IsInstanceOfType(value)) return value; // JsonElement from SignalR JSON protocol if (value is JsonElement element) return element.Deserialize(targetType, JsonOptions); // String → try JSON deserialization for complex types, direct conversion for simple if (value is string str && !IsSimpleType(targetType)) return JsonSerializer.Deserialize(str, targetType, JsonOptions); return ConvertValue(value, targetType, parameterName); } 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; } } Path: redb-route/redb.Route.Controllers/README.md 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/README.md ---- # redb.Route.Controllers > Documentation and articles: Transport-agnostic controller dispatch for the [redb.Route](../README.md) ESB framework. Provides a `RedbController` base class, attribute-based routing, parameter binding, and five dispatcher implementations for **generic**, **HTTP**, **SOAP**, **SignalR**, and **gRPC** transports with 16 DSL extension methods. Controllers are transport-unaware — the same controller class works behind any InOut endpoint. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Controllers?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Controllers) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Quick Start ```csharp // Define a controller [Route("orders")] public class OrdersController : RedbController { [HttpGet("{id}")] public Task GetOrder(int id) { return Task.FromResult(new Order { Id = id, Title = "Sample" }); } [HttpPost] public Task CreateOrder([FromBody] Order order) { // Access route context and exchange var ctx = Context; var exchange = Exchange; return Task.CompletedTask; } } // Register and dispatch (generic) var registry = new ControllerRegistry(); registry.RegisterAssembly(typeof(OrdersController).Assembly); route.From("direct://api") .RedbController(registry); // Or single controller shorthand route.From("direct://api") .RedbController(); ``` ## Architecture This is **not** a connector (no `IComponent`, no URI scheme, no producer/consumer). It is a processing library that provides `IProcessor` implementations and DSL extension methods. Controllers sit behind `direct:` or transport endpoints and dispatch based on headers set by the upstream consumer. ``` HTTP Consumer → [redbHttp.Method, redbHttp.Path] → HttpControllerDispatcher → OrdersController.GetOrder() SOAP Consumer → [redbSoap.operation] → SoapControllerDispatcher → AirController.GetFares() SignalR Hub → [redbSignalR.Method] → SignalRControllerDispatcher → ChatController.Send() gRPC Service → [dispatch-method] → GrpcControllerDispatcher → CalcController.Add() Any Endpoint → [route.method, route.path] → ControllerDispatcherProcessor → generic dispatch ``` ## RedbController Base Class All controllers inherit from `RedbController`, which exposes: | Property | Type | Description | |----------|------|-------------| | `Context` | `IRouteContext` | Route context for the current invocation | | `Exchange` | `IExchange` | Current exchange being processed | Controllers are instantiated per-request via `Activator.CreateInstance()`. No DI constructor injection — use `Context` to access services. ## Attributes ### Route Attribute Applied to the controller class. Sets the base path for all actions: ```csharp [Route("modules")] // explicit path public class ModulesController : RedbController { } // If omitted, defaults to class name minus "Controller" suffix, lowercased: public class UsersController : RedbController { } // base path: "users" ``` ### HTTP Method Attributes Applied to public methods. Define the HTTP method and optional sub-template: | Attribute | Method | Example | |-----------|--------|---------| | `[HttpGet]` | GET | `[HttpGet]`, `[HttpGet("{id}")]` | | `[HttpPost]` | POST | `[HttpPost]`, `[HttpPost("batch")]` | | `[HttpPut]` | PUT | `[HttpPut("{id}")]` | | `[HttpDelete]` | DELETE | `[HttpDelete("{id}")]` | | `[HttpPatch]` | PATCH | `[HttpPatch("{id}")]` | Templates support `{param}` placeholders that are extracted from the request path and matched to method parameters by name. ### Binding Attributes | Attribute | Source | Example | |-----------|--------|---------| | `[FromBody]` | `exchange.In.Body` | `[FromBody] Order order` | | `[FromHeader("X-Tenant")]` | `exchange.In.Headers["X-Tenant"]` | `[FromHeader("X-Tenant")] string tenant` | | `[FromQuery("page")]` | Query parameter | `[FromQuery("page")] int page` | | `[FromRoute("id")]` | Route template `{id}` | `[FromRoute("id")] int id` | | `[FromProperty("user")]` | `exchange.Properties["user"]` | `[FromProperty("user")] User user` | **Implicit binding** (no attribute): - `CancellationToken` → `CancellationToken.None` - Parameter name matches a route template `{param}` → bound from route - Complex type → deserialized from body - Simple type with default value → uses default **Conversion.** Header, query, route and property values are parsed with the invariant culture (`12.5` is twelve and a half on every server). A value that is missing binds as the parameter's default (or the type's). A value that is present but does not convert is a binding error naming the parameter and the value, as Camel's `ParameterBindingException`: the dispatchers answer `400`, SOAP a Sender fault, a direct invoke fails the exchange. ## Dispatchers ### ControllerDispatcherProcessor (Generic) Reads `route.path` and `route.method` headers. Works with any transport. ```csharp // Set headers before dispatch exchange.In.Headers["route.path"] = "orders/42"; exchange.In.Headers["route.method"] = "GET"; // DSL route.From("direct://api").RedbController(registry); route.From("direct://api").RedbController(); route.From("direct://api").RedbController("GetOrder"); // direct method call ``` ### HttpControllerDispatcher Reads `redbHttp.Method` and `redbHttp.Path` headers (set automatically by the HTTP consumer). Also merges `redbHttp.RouteParam.*` and reads `redbHttp.QueryParam.*` for parameter binding. ```csharp route.From("http://0.0.0.0:8080/api") .RedbHttpController(registry); route.From("http://0.0.0.0:8080/api") .RedbHttpController(); ``` ### SignalRControllerDispatcher Reads `redbSignalR.Method` header. Parameters are resolved positionally from the exchange body (as sent by the SignalR client). ```csharp route.From("signalr://bridge") .RedbSignalRController(); // Multiple controllers route.From("signalr://bridge") .RedbSignalRController(typeof(ChatController), typeof(NotificationController)); // Method resolution: "Send" or "Chat.Send" (qualified) ``` ### GrpcControllerDispatcher Reads `dispatch-method` header from gRPC metadata. Body is treated as JSON — single value or array of positional arguments. ```csharp route.From("grpc://0.0.0.0:5000") .RedbGrpcController(); // Multiple controllers route.From("grpc://0.0.0.0:5000") .RedbGrpcController(typeof(CalcController), typeof(DataController)); ``` ### SoapControllerDispatcher Reads the `redbSoap.operation` header (the `` root element's local name, set by the SOAP consumer) and dispatches to the method whose name — or `[SoapOperation("...")]` — matches. The XML body binds to the `[FromBody]` / single complex parameter via `XmlSerializer`, and the return value is XML-serialized into the response, which the SOAP consumer wraps in an envelope. A missing/unknown operation or an invocation exception throws, so the SOAP consumer returns a `soap:Fault`. ```csharp [Route("air")] public class AirController : RedbController { // Method name = SOAP operation; body binds from XML, reply serializes to XML. public Task GetFares([FromBody] GetFaresRequest req) => /* ... */; // Explicit operation name when it differs from the method name: [SoapOperation("HealthCheck")] public string Health() => "ok"; } // Behind a Soap.Listen(...) consumer: route.From(Soap.Listen("/svc/air").Host("0.0.0.0").Port(4090)) .RedbSoapController(); // Multiple controllers (qualified "Air.GetFares" disambiguates): route.From(Soap.Listen("/svc").Host("0.0.0.0").Port(4090)) .RedbSoapController(typeof(AirController), typeof(HotelController)); ``` DTOs are ordinary XML-serializable types (`[XmlRoot]` matching the request/response element), and may be generated from a WSDL with `dotnet-svcutil`. No HTTP attributes required. Use it behind a consumer in the default `Payload` data format. The dispatcher owns per-operation typing and the inner `` XML, so it is not meant to be combined with `Message` (whole-envelope) or `Pojo` (single fixed request type) mode. ## ControllerRegistry Builds a route lookup table by scanning assemblies or registering individual controller types: ```csharp var registry = new ControllerRegistry(); // Scan entire assembly int count = registry.RegisterAssembly(typeof(OrdersController).Assembly); // Or register individual controllers registry.RegisterController(typeof(OrdersController)); registry.RegisterController(typeof(UsersController)); // Resolve manually var action = registry.Resolve(HttpMethodType.Get, "orders/42", out var routeParams); // action.ControllerType = typeof(OrdersController) // action.Method = GetOrder // routeParams["id"] = "42" ``` ## Response Conventions These are the replies of the five **dispatchers** (generic, HTTP, SignalR, gRPC; SOAP answers faults instead of error bodies). They end the exchange as an API endpoint does. The direct-invoke overloads are route steps and follow the bean rules below instead. | Scenario | `status.code` | Body | |----------|---------------|------| | Method returns a value (`T`, `Task`, `ValueTask`) | `200` | Return value (JSON-serialized for HTTP/gRPC) | | Method returns `null`, `void`, `Task` or `ValueTask` | `204` | — (the request body is not echoed) | | Missing headers, or a value that does not bind | `400` | `ControllerErrorResponse` | | No matching action | `404` | `ControllerErrorResponse` | | Exception during invocation | `500` | `ControllerErrorResponse` | An action may answer by itself: write `Exchange.Out` (body, status, headers), call `Exchange.Stop()` and return `null`. The dispatcher keeps that reply as it is and only fills in a missing `status.code` and `Content-Type`. ```csharp // Error response model public sealed class ControllerErrorResponse { public string Error { get; init; } // e.g. "NotFound", "BadRequest", "InternalError" public string Message { get; init; } // Human-readable description public int StatusCode { get; init; } // HTTP status code } ``` ## DSL Extension Methods All methods are on `IRouteDefinition`: | Method | Dispatcher | Headers Read | |--------|-----------|--------------| | `RedbController(registry)` | Generic | `route.path`, `route.method` | | `RedbController()` | Generic | `route.path`, `route.method` | | `RedbController(methodName)` | Direct invoke | — | | `RedbController(registry, ctrlName, methodName)` | Direct invoke | — | | `RedbController(registry, ctrlExpr, methodExpr)` | Dynamic | Exchange-dependent | | `RedbHttpController(registry)` | HTTP | `redbHttp.Method`, `redbHttp.Path` | | `RedbHttpController()` | HTTP | `redbHttp.Method`, `redbHttp.Path` | | `RedbSignalRController()` | SignalR | `redbSignalR.Method` | | `RedbSignalRController(types)` | SignalR | `redbSignalR.Method` | | `RedbSignalRController(registry)` | SignalR | `redbSignalR.Method` | | `RedbSoapController()` | SOAP | `redbSoap.operation` | | `RedbSoapController(types)` | SOAP | `redbSoap.operation` | | `RedbSoapController(registry)` | SOAP | `redbSoap.operation` | | `RedbGrpcController()` | gRPC | `dispatch-method` | | `RedbGrpcController(types)` | gRPC | `dispatch-method` | | `RedbGrpcController(registry)` | gRPC | `dispatch-method` | ### Direct invoke is a bean step `RedbController(methodName)`, `RedbController(registry, ctrlName, methodName)` and `RedbController(registry, ctrlExpr, methodExpr)` call one method as a step in the middle of a route, the way the core's `.Bean(...)` and the `bean:` endpoint do (Camel's `.bean(...)`), with the controller conveniences on top: an instance per exchange, `Context`/`Exchange` set, and the binding attributes above. | Method returns | Message after the step | |----------------|------------------------| | a value (`T`, `Task`, `ValueTask`) | the value is the body, `status.code` = `200` | | `null`, `void`, `Task` or `ValueTask` | unchanged: the next step sees what this one received | | throws | the exchange fails with the action's own exception, so `OnException(typeof(...))` matches it | ```csharp // The audit step records and passes the order on untouched; the pricing step replaces the body. route.From("direct://orders") .RedbController(nameof(AuditController.Record)) // void .RedbController(nameof(PricingController.Quote)) // returns a Quote .To("direct://billing"); ``` ## Requirements - .NET 10.0 / 11.0. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet. - `redb.Route` (core) — no external dependencies Path: redb-route/redb.Route.Controllers/RedbController.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/RedbController.cs ---- using redb.Route.Abstractions; namespace redb.Route.Controllers; /// /// Base class for transport-agnostic controllers dispatched via . /// Controllers sit behind direct: endpoints and are unaware of transport — any InOut endpoint can invoke them. /// public abstract class RedbController { /// Route context this controller operates within. public IRouteContext Context { get; internal set; } = null!; /// Current exchange being processed. public IExchange Exchange { get; internal set; } = null!; } Path: redb-route/redb.Route.Controllers/SignalRControllerDispatcher.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/SignalRControllerDispatcher.cs ---- using System.Collections.Frozen; using System.Reflection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Controllers; /// /// Dispatches SignalR hub invocations to controller methods by name. /// Reads the method name from redbSignalR.Method header and resolves positional arguments /// from the exchange body (as set by RedbBridgeHub.Invoke). /// /// Single controller: method name is looked up directly (e.g. "GetAll"). /// Multiple controllers: qualified format "Controller.Method" (e.g. "Modules.GetAll") /// is preferred; unqualified names resolve to first match. /// /// public sealed class SignalRControllerDispatcher : IProcessor { private readonly FrozenDictionary _methods; private readonly IRouteContext _context; private readonly ILogger? _logger; /// Header key for the SignalR method name (matches SignalRHeaders.Method). internal const string MethodHeader = "redbSignalR.Method"; /// Route context for controller instantiation. /// One or more controller types to register. public SignalRControllerDispatcher(IRouteContext context, params Type[] controllerTypes) { _context = context ?? throw new ArgumentNullException(nameof(context)); if (controllerTypes is null || controllerTypes.Length == 0) throw new ArgumentException("At least one controller type is required.", nameof(controllerTypes)); _methods = BuildMethodMap(controllerTypes); _logger = ControllerErrorReporting.CreateLogger(context); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var methodName = exchange.In.GetHeader(MethodHeader); if (string.IsNullOrEmpty(methodName)) { WriteError(exchange, 400, "BadRequest", $"Missing required header: {MethodHeader}"); return; } if (!_methods.TryGetValue(methodName, out var entry)) { WriteError(exchange, 404, "NotFound", $"Method '{methodName}' not found on registered controllers"); return; } // Binding failures are the caller's 400, action failures are our 500 — the boundary is // the resolution step, same as the HTTP dispatcher. object?[] parameters; try { parameters = ParameterResolver.ResolvePositional(entry.Method, exchange.In.Body, ct); } catch (Exception ex) when (ex is not OperationCanceledException) { WriteError(exchange, 400, ControllerErrorReporting.BadRequestCode, ControllerErrorReporting.ReportBadRequest(_logger, ex, exchange, methodName)); return; } try { var controller = (RedbController)Activator.CreateInstance(entry.ControllerType)!; controller.Context = _context; controller.Exchange = exchange; // The action's own exception, one TargetInvocationException removed (see ActionInvoker). var result = await ActionInvoker.InvokeAsync(entry.Method, controller, parameters); WriteResult(exchange, result); } catch (Exception ex) { WriteError(exchange, 500, ControllerErrorReporting.ErrorCode, ControllerErrorReporting.Report(_logger, ex, exchange, methodName)); } } private static FrozenDictionary BuildMethodMap(Type[] controllerTypes) { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var type in controllerTypes) { if (!type.IsSubclassOf(typeof(RedbController))) throw new ArgumentException($"Type '{type.Name}' does not inherit from RedbController."); var controllerName = type.Name.EndsWith("Controller", StringComparison.Ordinal) ? type.Name[..^10] : type.Name; foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var entry = new MethodEntry(type, method); // Qualified name: "Modules.GetAll" — always registered, last-write wins per controller map[$"{controllerName}.{method.Name}"] = entry; // Short name: "GetAll" — only if no collision across controllers map.TryAdd(method.Name, entry); } } return map.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); } private static 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, // with its own body and status. Only a clone the dispatcher makes here carries the request body. var createdHere = exchange.Out is null; exchange.Out ??= exchange.In.Clone(); if (result is null) { if (createdHere) exchange.Out.Body = null; // our own clone of the request is not the reply if (!exchange.Out.Headers.ContainsKey("status.code")) exchange.Out.setHeader("status.code", 204); return; } exchange.Out.Body = result; exchange.Out.setHeader("status.code", 200); } private static void WriteError(IExchange exchange, int statusCode, string error, string message) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = new ControllerErrorResponse { Error = error, Message = message, StatusCode = statusCode }; exchange.Out.setHeader("status.code", statusCode); } internal sealed record MethodEntry(Type ControllerType, MethodInfo Method); } Path: redb-route/redb.Route.Controllers/SoapControllerDispatcher.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/SoapControllerDispatcher.cs ---- using System.Collections.Concurrent; using System.Collections.Frozen; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Serialization; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Controllers.Attributes; namespace redb.Route.Controllers; /// /// Dispatches SOAP requests to controller methods by operation name, making SOAP a first-class controller /// transport alongside HTTP, SignalR and gRPC. The operation is read from redbSoap.operation (the local /// name of the <soap:Body> root element, which the SOAP consumer sets); it maps to a method whose /// name — or — matches. The request body is XML and binds to the method's /// [FromBody] (or single complex) parameter via ; the return value is /// XML-serialized onto , which the SOAP consumer wraps in a response envelope. /// A missing operation, an unknown operation, or an invocation exception throws — the SOAP consumer turns that /// into a soap:Fault. /// /// Use it behind a consumer in the default Payload data format: the dispatcher owns per-operation typing /// and the inner <soap:Body> XML, which is what Payload delivers. It is not meant to be /// combined with Message (which hands over the whole envelope and sends the reply without wrapping) or /// Pojo (which fixes one request type on the endpoint and so collapses multi-operation dispatch). /// /// public sealed class SoapControllerDispatcher : IProcessor { /// Header the SOAP consumer sets to the request operation (Body root element local name). public const string OperationHeader = "redbSoap.operation"; // Weak per type: a type of an unloadable module (collectible load context) does not stay alive in this cache. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Serializers = new(); private readonly FrozenDictionary _operations; private readonly IRouteContext _context; /// Route context for controller instantiation. /// One or more controller types to register. public SoapControllerDispatcher(IRouteContext context, params Type[] controllerTypes) { _context = context ?? throw new ArgumentNullException(nameof(context)); if (controllerTypes is null || controllerTypes.Length == 0) throw new ArgumentException("At least one controller type is required.", nameof(controllerTypes)); _operations = BuildOperationMap(controllerTypes); _logger = ControllerErrorReporting.CreateLogger(context); } private readonly Microsoft.Extensions.Logging.ILogger? _logger; /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader(OperationHeader); if (string.IsNullOrEmpty(operation)) throw new InvalidOperationException( $"SOAP dispatch requires the '{OperationHeader}' header (set by the SOAP consumer)."); if (!_operations.TryGetValue(operation, out var entry)) throw new InvalidOperationException($"No SOAP operation '{operation}' on the registered controllers."); var controller = (RedbController)Activator.CreateInstance(entry.ControllerType)!; controller.Context = _context; controller.Exchange = exchange; // Binding failures on the CALLER's bytes surface as MalformedRequestException, which the SOAP // consumer maps to a Sender/Client fault carrying this message instead of the Receiver fault // with a generic text that an unhandled exception becomes — the HTTP dispatcher's 400, in SOAP // terms. ResolveArgs draws the line itself: a signature no request could ever bind (a required // simple parameter with no source) is the controller author's error and stays a Receiver fault. object?[] args; try { args = ResolveArgs(entry.Method, exchange, ct, operation); } catch (MalformedRequestException ex) { _logger?.LogWarning( "Malformed SOAP request for {Operation} (exchange {ExchangeId}): {Reason}", operation, exchange.ExchangeId, ex.Message); throw; } // Task, ValueTask and their results are read from the declared return type, and a sync throw reaches the // consumer as the action's own exception (see ActionInvoker). var result = await ActionInvoker.InvokeAsync(entry.Method, controller, args).ConfigureAwait(false); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = SerializeResult(result); exchange.Out.ContentType = "text/xml"; } private static object?[] ResolveArgs(MethodInfo method, IExchange exchange, CancellationToken ct, string operation) { var parameters = method.GetParameters(); var values = new object?[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { var p = parameters[i]; if (p.ParameterType == typeof(CancellationToken)) { values[i] = ct; continue; } // Header binding shares the JSON dispatchers' value conversion. The header value is the // caller's data: a value that does not convert is THEIR malformed request, not our failure. if (p.GetCustomAttribute() is { } h) { var raw = exchange.In.getHeader(h.Name); try { values[i] = raw is not null ? ParameterResolver.ConvertValue(raw, p.ParameterType) : (p.HasDefaultValue ? p.DefaultValue : ParameterResolver.ConvertValue(null, p.ParameterType)); } catch (Exception ex) when (ex is not OperationCanceledException) { throw new MalformedRequestException( $"Malformed request for operation '{operation}': header '{h.Name}' does not bind to " + $"parameter '{p.Name}' ({p.ParameterType.Name}): {ex.Message}", ex); } continue; } // The SOAP Body is XML: [FromBody] or a single complex parameter deserializes from it. // The body is the caller's bytes too — XML that does not parse is their malformed request. if (p.GetCustomAttribute() is not null || !IsSimpleType(p.ParameterType)) { try { values[i] = DeserializeXml(exchange.In.Body, p.ParameterType); } catch (Exception ex) when (ex is not OperationCanceledException) { throw new MalformedRequestException( $"Malformed request for operation '{operation}': the request body does not " + $"deserialize to '{p.ParameterType.Name}': {ex.Message}", ex); } continue; } if (p.HasDefaultValue) { values[i] = p.DefaultValue; continue; } // A required simple parameter with no binding cannot come from the XML body. Fail with a readable // message (which becomes the soap:Fault reason) instead of a cryptic reflection ArgumentException. var t = p.ParameterType; if (t.IsValueType && Nullable.GetUnderlyingType(t) is null) throw new InvalidOperationException( $"SOAP operation cannot bind parameter '{p.Name}' of type '{t.Name}': annotate it with " + "[FromHeader], or give it a default value. The SOAP body binds to the [FromBody] / complex parameter."); values[i] = null; } return values; } private static object? DeserializeXml(object? body, Type type) { if (body is null) return null; if (type.IsInstanceOfType(body)) return body; var xml = body switch { string s => s, byte[] b => Encoding.UTF8.GetString(b), _ => body.ToString() ?? string.Empty, }; if (string.IsNullOrWhiteSpace(xml)) return null; if (type == typeof(string)) return xml; using var sr = new StringReader(xml); return Serializer(type).Deserialize(sr); } private static object? SerializeResult(object? result) { if (result is null) return string.Empty; if (result is string s) return s; if (result is byte[]) return result; var ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); // drop xsi/xsd noise, keep the type's namespace var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false }; using var sw = new StringWriter(); using (var xw = XmlWriter.Create(sw, settings)) Serializer(result.GetType()).Serialize(xw, result, ns); return sw.ToString(); } private static XmlSerializer Serializer(Type t) => Serializers.GetValue(t, static x => new XmlSerializer(x)); private static FrozenDictionary BuildOperationMap(Type[] controllerTypes) { // Case-SENSITIVE: the operation is the Body root element's local name, and XML names are case-sensitive. var map = new Dictionary(StringComparer.Ordinal); var owners = new Dictionary(StringComparer.Ordinal); // op -> "Controller.Method" that claimed it foreach (var type in controllerTypes) { if (!type.IsSubclassOf(typeof(RedbController))) throw new ArgumentException($"Type '{type.Name}' does not inherit from RedbController."); var controllerName = type.Name.EndsWith("Controller", StringComparison.Ordinal) ? type.Name[..^10] : type.Name; foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var op = method.GetCustomAttribute()?.Operation ?? method.Name; // Dispatch is by the unqualified operation only (the qualified "Controller.op" form is never on // the wire), so a duplicate is an unresolvable ambiguity: fail fast rather than silently run the // first-registered handler for another controller's request. if (owners.TryGetValue(op, out var owner)) throw new InvalidOperationException( $"Ambiguous SOAP operation '{op}': claimed by both {owner} and {controllerName}.{method.Name}. " + "Operation names must be unique across controllers on one endpoint; use [SoapOperation(\"...\")] to disambiguate."); owners[op] = $"{controllerName}.{method.Name}"; map[op] = new MethodEntry(type, method); } } return map.ToFrozenDictionary(StringComparer.Ordinal); } 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; } internal sealed record MethodEntry(Type ControllerType, MethodInfo Method); } Path: redb-route/redb.Route.Controllers/redb.Route.Controllers.csproj 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/redb.Route.Controllers.csproj ---- redb.Route.Controllers Transport-agnostic controller dispatch for redb.Route ESB framework. Provides RedbController base class, attribute-based routing, parameter binding, and ControllerDispatcherProcessor. esb;messaging;controllers;dispatch;routing;redb README.md