- 新增二维码生成端点,自动检测局域网 IP,前端扫一扫即可打开网站 - 提取 IApiResponse 接口,ServiceRequestBinder 支持强类型请求 DTO 绑定 - FileStream 端点迁移至 AppEndpoints 统一注册,管道支持 FileStreamResponse 原始文件返回 - 文件库端点全面使用 MapGet<TService, TRequest> 泛型注册 - 移除 Avalonia-API/Extensions 中的业务端点文件,统一由 Services 层管理
54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace Avalonia_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);
|
|
}
|
|
}
|
|
}
|
|
}
|