54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace FileShare_Services.Core
|
|
{
|
|
/// <summary>
|
|
/// Binds unified endpoint request models from JSON bodies or query parameters.
|
|
/// </summary>
|
|
internal static class ServiceRequestBinder
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
|
{
|
|
NumberHandling = JsonNumberHandling.AllowReadingFromString,
|
|
};
|
|
|
|
/// <summary>
|
|
/// Bind a JSON request body. Empty bodies are treated as an empty JSON object.
|
|
/// </summary>
|
|
public static T BindBody<T>(ServiceEndpointContext context)
|
|
{
|
|
var json = string.IsNullOrWhiteSpace(context.Body) ? "{}" : context.Body;
|
|
return Deserialize<T>(json, "body");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Bind route and query parameters to a request DTO.
|
|
/// </summary>
|
|
public static T BindQuery<T>(ServiceEndpointContext context)
|
|
{
|
|
var values = new Dictionary<string, string>(context.Query, StringComparer.OrdinalIgnoreCase);
|
|
foreach (var routeValue in context.RouteValues)
|
|
{
|
|
values[routeValue.Key] = routeValue.Value;
|
|
}
|
|
|
|
var json = JsonSerializer.Serialize(values, JsonOptions);
|
|
return Deserialize<T>(json, "query");
|
|
}
|
|
|
|
private static T Deserialize<T>(string json, string source)
|
|
{
|
|
try
|
|
{
|
|
return JsonSerializer.Deserialize<T>(json, JsonOptions)
|
|
?? throw new ArgumentException($"Request {source} cannot be bound to {typeof(T).Name}.");
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
throw new ArgumentException($"Request {source} cannot be bound to {typeof(T).Name}.", ex);
|
|
}
|
|
}
|
|
}
|
|
}
|