统一服务端点架构,支持多端接口与数据库切换
重构项目结构,引入 Avalonia-Common、Avalonia-EFCore、Avalonia-Services,实现 API 与桌面端统一端点注册、过滤器、鉴权和标准响应格式。支持多数据库自动迁移与配置,集成 Serilog 日志系统。移除旧路由与控制器,提升接口一致性与可维护性。
This commit is contained in:
@@ -9,10 +9,17 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Avalonia-Services\Avalonia-Services.csproj" />
|
||||
<ProjectReference Include="..\Avalonia-Common\Avalonia-Common.csproj" />
|
||||
<ProjectReference Include="..\Avalonia-EFCore\Avalonia-EFCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Controllers\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>https</ActiveDebugProfile>
|
||||
<ActiveDebugProfile>http</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,15 +1,38 @@
|
||||
using Avalonia_Services.Services;
|
||||
using Avalonia_EFCore.Database;
|
||||
using Avalonia_Services.Core;
|
||||
using Avalonia_Services.Database;
|
||||
using Avalonia_Services.Endpoints;
|
||||
using Avalonia_Services.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Avalonia_API.Configuration
|
||||
{
|
||||
public static class ServicesConfiguration
|
||||
{
|
||||
public static void ConfigureServices(this IServiceCollection services)
|
||||
/// <summary>
|
||||
/// 注册统一端点及其依赖的服务(含数据库)。
|
||||
/// 所有业务端点定义在 Avalonia-Services/Endpoints/AppEndpoints.cs。
|
||||
/// </summary>
|
||||
public static IServiceCollection AddUnifiedApiServices(this IServiceCollection services)
|
||||
{
|
||||
// Register your services here
|
||||
// For example:
|
||||
// services.AddSingleton<IMyService, MyService>();
|
||||
// ---- 数据库 ----
|
||||
// 从 appsettings.json 读取 DatabaseConfiguration 节
|
||||
// 注册默认数据库提供程序(SQLite / MySQL / PostgreSQL / SqlServer)
|
||||
DatabaseProviderRegistry.RegisterDefaults();
|
||||
|
||||
// 注册 AppDataContext(共享数据上下文)
|
||||
services.AddAppDatabase<AppDataContext>(DatabaseConfiguration.ForSQLite("app.db"));
|
||||
|
||||
// ---- 业务服务 ----
|
||||
services.AddScoped<WeatherForecastService>();
|
||||
|
||||
// ---- 统一端点 ----
|
||||
var endpointBuilder = new ServiceEndpointBuilder();
|
||||
AppEndpoints.Configure(endpointBuilder);
|
||||
var endpoints = endpointBuilder.Build();
|
||||
services.AddSingleton(endpoints);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
using Avalonia_Services.Models;
|
||||
using Avalonia_Services.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Avalonia_API.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController(WeatherForecastService weatherForecastService) : ControllerBase
|
||||
{
|
||||
|
||||
private readonly WeatherForecastService _weatherForecastService = weatherForecastService;
|
||||
|
||||
[HttpGet(Name = "GetWeatherForecast")]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
return _weatherForecastService.GetWeatherForecasts();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using Avalonia_Services.Core;
|
||||
using AspNetCoreFilterContext = Microsoft.AspNetCore.Http.EndpointFilterInvocationContext;
|
||||
using AspNetCoreFilterDelegate = Microsoft.AspNetCore.Http.EndpointFilterDelegate;
|
||||
// 解决与 ASP.NET Core 同名类型的冲突
|
||||
using UnifiedFilter = Avalonia_Services.Core.IEndpointFilter;
|
||||
|
||||
namespace Avalonia_API.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 将 Avalonia-Services 的统一端点映射到 ASP.NET Core Minimal API。
|
||||
/// 支持鉴权、过滤器、中间件的完整 ASP.NET Core 管道。
|
||||
/// </summary>
|
||||
public static class UnifiedEndpointExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 将 ServiceEndpointCollection 中的所有端点注册到 ASP.NET Core 路由。
|
||||
/// </summary>
|
||||
public static IEndpointRouteBuilder MapUnifiedEndpoints(
|
||||
this IEndpointRouteBuilder routeBuilder,
|
||||
ServiceEndpointCollection endpoints,
|
||||
IServiceProvider serviceProvider)
|
||||
{
|
||||
var apiGroup = routeBuilder.MapGroup("/");
|
||||
|
||||
foreach (var endpoint in endpoints.Endpoints)
|
||||
{
|
||||
var routeHandlerBuilder = MapEndpoint(apiGroup, endpoint, serviceProvider);
|
||||
|
||||
// 全局过滤器 → ASP.NET Core Endpoint Filters
|
||||
foreach (var globalFilter in endpoints.GlobalFilters)
|
||||
{
|
||||
routeHandlerBuilder.AddEndpointFilter(
|
||||
async (context, next) => await ConvertFilterAsync(globalFilter, context, next));
|
||||
}
|
||||
|
||||
// 端点专属过滤器
|
||||
foreach (var filter in endpoint.Filters)
|
||||
{
|
||||
routeHandlerBuilder.AddEndpointFilter(
|
||||
async (context, next) => await ConvertFilterAsync(filter, context, next));
|
||||
}
|
||||
|
||||
// 鉴权(使用 ASP.NET Core 原生鉴权机制)
|
||||
if (endpoint.RequireAuthorization)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(endpoint.Policy))
|
||||
{
|
||||
routeHandlerBuilder.RequireAuthorization(endpoint.Policy);
|
||||
}
|
||||
else
|
||||
{
|
||||
routeHandlerBuilder.RequireAuthorization();
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(endpoint.Name))
|
||||
{
|
||||
routeHandlerBuilder.WithName(endpoint.Name);
|
||||
}
|
||||
}
|
||||
|
||||
return routeBuilder;
|
||||
}
|
||||
|
||||
private static RouteHandlerBuilder MapEndpoint(
|
||||
IEndpointRouteBuilder group,
|
||||
ServiceEndpoint endpoint,
|
||||
IServiceProvider serviceProvider)
|
||||
{
|
||||
var handler = CreateAspNetCoreHandler(endpoint.Handler, serviceProvider);
|
||||
|
||||
return endpoint.HttpMethod.ToUpperInvariant() switch
|
||||
{
|
||||
"GET" => group.MapGet(endpoint.Pattern, handler),
|
||||
"POST" => group.MapPost(endpoint.Pattern, handler),
|
||||
"PUT" => group.MapPut(endpoint.Pattern, handler),
|
||||
"DELETE" => group.MapDelete(endpoint.Pattern, handler),
|
||||
_ => group.MapGet(endpoint.Pattern, handler),
|
||||
};
|
||||
}
|
||||
|
||||
private static Delegate CreateAspNetCoreHandler(
|
||||
Func<ServiceEndpointContext, Task<object?>> unifiedHandler,
|
||||
IServiceProvider serviceProvider)
|
||||
{
|
||||
return async (HttpContext httpContext) =>
|
||||
{
|
||||
var ctx = await BuildContextFromHttpContext(httpContext);
|
||||
ctx.Items["ServiceProvider"] = serviceProvider;
|
||||
|
||||
var result = await unifiedHandler(ctx);
|
||||
|
||||
// 同步响应状态
|
||||
httpContext.Response.StatusCode = ctx.StatusCode;
|
||||
foreach (var kvp in ctx.ResponseHeaders)
|
||||
{
|
||||
httpContext.Response.Headers[kvp.Key] = kvp.Value;
|
||||
}
|
||||
|
||||
return result is not null ? Results.Json(result) : Results.Ok();
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<ServiceEndpointContext> BuildContextFromHttpContext(HttpContext httpContext)
|
||||
{
|
||||
var ctx = new ServiceEndpointContext
|
||||
{
|
||||
Path = httpContext.Request.Path.Value ?? "/",
|
||||
Method = httpContext.Request.Method,
|
||||
StatusCode = 200,
|
||||
};
|
||||
|
||||
foreach (var header in httpContext.Request.Headers)
|
||||
{
|
||||
ctx.Headers[header.Key] = header.Value.ToString();
|
||||
}
|
||||
|
||||
foreach (var query in httpContext.Request.Query)
|
||||
{
|
||||
ctx.Query[query.Key] = query.Value.ToString();
|
||||
}
|
||||
|
||||
if (httpContext.Request.ContentLength > 0)
|
||||
{
|
||||
using var reader = new StreamReader(httpContext.Request.Body);
|
||||
ctx.Body = await reader.ReadToEndAsync();
|
||||
}
|
||||
|
||||
ctx.Items["HttpContext"] = httpContext;
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static async ValueTask<object?> ConvertFilterAsync(
|
||||
UnifiedFilter unifiedFilter,
|
||||
AspNetCoreFilterContext aspContext,
|
||||
AspNetCoreFilterDelegate aspNext)
|
||||
{
|
||||
var httpContext = aspContext.HttpContext;
|
||||
var ctx = httpContext.Items["UnifiedContext"] as ServiceEndpointContext
|
||||
?? await BuildContextFromHttpContext(httpContext);
|
||||
|
||||
httpContext.Items["UnifiedContext"] = ctx;
|
||||
|
||||
await unifiedFilter.InvokeAsync(ctx, async (c) =>
|
||||
{
|
||||
httpContext.Response.StatusCode = c.StatusCode;
|
||||
foreach (var kvp in c.ResponseHeaders)
|
||||
{
|
||||
httpContext.Response.Headers[kvp.Key] = kvp.Value;
|
||||
}
|
||||
await aspNext(aspContext);
|
||||
});
|
||||
|
||||
if (ctx.ResponseBody is not null)
|
||||
{
|
||||
return Results.Json(ctx.ResponseBody, statusCode: ctx.StatusCode);
|
||||
}
|
||||
|
||||
return null!;
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
-19
@@ -1,23 +1,57 @@
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
using Avalonia_API.Configuration;
|
||||
using Avalonia_API.Extensions;
|
||||
using Avalonia_Common.Infrastructure;
|
||||
using Avalonia_EFCore.Database;
|
||||
using Avalonia_Services.Core;
|
||||
using Avalonia_Services.Database;
|
||||
using Serilog;
|
||||
|
||||
// Add services to the container.
|
||||
// 初始化日志系统
|
||||
Log.Logger = LoggingConfiguration.CreateDefaultLogger(logDir: "logs");
|
||||
Log.Information("Avalonia-API 正在启动...");
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
try
|
||||
{
|
||||
app.MapOpenApi();
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 使用 Serilog 作为日志提供程序
|
||||
builder.Host.UseSerilog();
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
// 注册统一端点及业务服务(入口在 Avalonia-Services/Endpoints/AppEndpoints.cs)
|
||||
builder.Services.AddUnifiedApiServices();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// 初始化数据库(自动迁移 + 种子数据)
|
||||
app.Services.InitializeDatabase<AppDataContext>();
|
||||
|
||||
// 启动时打印所有接口
|
||||
var endpoints = app.Services.GetRequiredService<ServiceEndpointCollection>();
|
||||
EndpointPrinter.PrintEndpoints(endpoints, "Avalonia-API 接口列表");
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthorization();
|
||||
|
||||
// 将统一端点映射到 ASP.NET Core 路由
|
||||
app.MapUnifiedEndpoints(endpoints, app.Services);
|
||||
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "Avalonia-API 启动失败");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -5,5 +5,12 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"DatabaseConfiguration": {
|
||||
"Provider": "SQLite",
|
||||
"ConnectionString": "Data Source=avalonia-api.db",
|
||||
"AutoMigrate": true,
|
||||
"EnableDetailedLog": false,
|
||||
"Timeout": 30
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
2026-05-11 13:39:27.320 [INF] Avalonia-API 正在启动...
|
||||
2026-05-11 13:39:58.813 [INF] Avalonia-API 正在启动...
|
||||
2026-05-11 13:40:13.058 [INF] Avalonia-API 正在启动...
|
||||
2026-05-11 13:40:13.566 [INF] Now listening on: http://localhost:5206
|
||||
2026-05-11 13:40:13.603 [INF] No action descriptors found. This may indicate an incorrectly configured application or missing application parts. To learn more, visit https://aka.ms/aspnet/mvc/app-parts
|
||||
2026-05-11 13:40:13.633 [INF] Application started. Press Ctrl+C to shut down.
|
||||
2026-05-11 13:40:13.635 [INF] Hosting environment: Development
|
||||
2026-05-11 13:40:13.635 [INF] Content root path: D:\QiChengProject\Avalonia-Stack\Avalonia-API
|
||||
Reference in New Issue
Block a user