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