Galosys.Foundation.AspNetCore
26.9.3.1
dotnet add package Galosys.Foundation.AspNetCore --version 26.9.3.1
NuGet\Install-Package Galosys.Foundation.AspNetCore -Version 26.9.3.1
<PackageReference Include="Galosys.Foundation.AspNetCore" Version="26.9.3.1" />
<PackageVersion Include="Galosys.Foundation.AspNetCore" Version="26.9.3.1" />
<PackageReference Include="Galosys.Foundation.AspNetCore" />
paket add Galosys.Foundation.AspNetCore --version 26.9.3.1
#r "nuget: Galosys.Foundation.AspNetCore, 26.9.3.1"
#:package Galosys.Foundation.AspNetCore@26.9.3.1
#addin nuget:?package=Galosys.Foundation.AspNetCore&version=26.9.3.1
#tool nuget:?package=Galosys.Foundation.AspNetCore&version=26.9.3.1
Galosys.Foundation.AspNetCore
目标框架:
net10.0
成熟度: 🟢 稳定 — 生产可用,测试充分,活跃维护
简介
Galosys.Foundation.AspNetCore 是 ASP.NET Core 核心扩展模块,提供 MVC 过滤器、身份认证、SignalR 中间件等功能。授权能力由 Galosys.Foundation.AspNetCore.Authorization(ABAC)模块提供(见「权限控制」)。
特性
MVC 过滤器
- GlobalResponseLoggingResultFilter - 响应日志记录
- GlobalLogExceptionFilter - 全局异常日志
- GlobalModelStateValidationActionFilter - 模型状态验证
- AuditLogAttribute - 审计日志
- RequestLogAttribute - 请求日志
- CacheableAttribute - 响应缓存(支持多租户 Key 隔离,HybridCache 内置击穿保护,可选布隆过滤器)
- CacheEvictAttribute - 缓存清除(支持多租户 Key 隔离)
- CachePutAttribute - 缓存写入(支持多租户 Key 隔离)
- SensitiveAttribute + SensitiveDataFilter - API 响应敏感字段自动脱敏(手机/身份证/邮箱等)
- RateLimitAttribute - 声明式限流元数据,配合
GlobalLimiter按用户/租户粒度限流 - IdempotentAttribute - 幂等性验证
身份认证
- JWT Bearer - JWT 认证支持
- HttpBasic - HTTP 基本认证
- ApiKey - API Key 认证
权限管理
授权能力由 Galosys.Foundation.AspNetCore.Authorization(ABAC)模块提供——使用方显式调用 AddAuthorizationEngine(),policy 名即策略名(见设计文档 abac-design.md 4.2)。
SignalR
- SignalR Hub - 实时通信
- SignalR Client - 客户端支持
多租户(MultiTenancy)
- AddMultiTenancy() - 多租户完整栈注册入口(
Microsoft.AspNetCore.MultiTenancy寄生命名空间,兼容层合并自已删除的Galosys.Foundation.AspNetCore.MultiTenancy孤儿包) - HeaderResolutionStrategy / HostResolutionStrategy / CompositeTenantResolutionStrategy - HTTP Header / Host / 组合式租户解析策略(
Microsoft.AspNetCore.MultiTenancy.Resolution) - JwtClaimResolutionStrategy / RouteResolutionStrategy / QueryStringResolutionStrategy / CookieResolutionStrategy / SubdomainResolutionStrategy - JWT Claim / 路由值 / 查询参数 / Cookie / 子域租户解析策略(
Microsoft.AspNetCore.MultiTenancy.Resolution) - TenantBuilder - 链式配置解析策略与存储(WithHeader / WithHost / WithJwtClaim / WithRoute / WithQueryString / WithCookie / WithSubdomain / WithResolutionStrategy / WithStore)
- TenantAccessService / ITenantAccessor / TenantAccessor - 租户查询服务与访问器
- MultiTenancyMiddleware - 多租户中间件(非泛型,按注册顺序遍历解析策略,命中后设置租户上下文)
- GetTenant() -
HttpContext扩展,取当前请求租户 - 详见
docs/adr/0003-multitenancy-isolation-strategies.md与docs/designs/multi-tenancy-enhancement.md(附录 A 选型决策)
中间件
- CorrelationIdMiddleware - 跨服务请求链路 CorrelationId 生成与透传
- GlobalExceptionHandlerMiddleware - 全局异常处理
- MultiTenancyMiddleware - 多租户支持
- LoginUserMiddleware - 登录用户中间件
- CorsMiddleware - CORS 配置
- SensitiveDataFilter - API 响应敏感字段自动脱敏(IAlwaysRunResultFilter)
安装
dotnet add package Galosys.Foundation.AspNetCore
使用
注册服务
services.AddAspNetCore(); // 注册所有服务
配置 JWT 认证
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://auth.example.com";
options.Audience = "api.example.com";
});
配置 SignalR
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapHubs();
});
使用审计日志
[AuditLog("创建订单")]
public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
{
// 业务逻辑,审计日志自动通过 ReliableLogChannel 异步持久化
}
// 设置审计前后值
HttpContext.SetAuditValues(originalValues, currentValues, targetId);
审计日志持久化
审计日志通过 Tier 2 可靠通道异步持久化,失败自动重试(指数退避,最多 3 次)。需注册通道和实现 IAuditLogRepository:
// 注册通道 + 消费者(通常在 Startup 中)
services.AddAuditLogChannel();
// 实现持久化接口
public class AuditLogRepository : IAuditLogRepository
{
public Task AddAsync(AuditLog auditLog, CancellationToken ct = default)
{
// 写入 lc.lc_audit_log 表
}
}
使用请求日志
[RequestLog("订单API")]
public async Task<IActionResult> ListOrders([FromQuery] OrderQuery query)
{
// 请求日志自动通过 ObservableLogChannel 批量持久化
}
请求日志持久化
请求日志通过 Tier 1 可观测通道批量持久化。需注册通道和实现 IRequestLogRepository:
services.AddRequestLogChannel();
public class RequestLogRepository : IRequestLogRepository
{
public Task AddRangeAsync(IReadOnlyList<RequestLogCreateInput> inputs, CancellationToken ct = default)
{
// 批量写入 lc.lc_api_request_log 表
}
}
使用登录日志
// 替代旧版 GetUserLoginEvent + publisher.PublishAsync
await HttpContext.PublishLoginLogAsync(realName, status: 1, remark: "登录成功");
登录日志通过 Tier 2 可靠通道持久化。需注册通道和实现 ILoginLogRepository(AddCore() 内置注册通道)。
使用 CorrelationId 链路透传
CorrelationIdMiddleware 已自动集成在 UseAspNetCore() 管道中(位于 UseLocalization() 之后),无需手动注册。支持自定义 Header 名称:
app.UseCorrelationId(options =>
{
options.Header = "X-Request-Id"; // 读取的请求 Header
options.ResponseHeader = "X-Request-Id"; // 写入的响应 Header
options.IncludeInResponse = true; // 是否在响应中包含
});
CorrelationId 自动写入 HttpContext.Items["CorrelationId"] 和日志上下文(ILogger.BeginScope)。
使用敏感数据脱敏
在 Model 属性上标注 [Sensitive],API 返回时自动脱敏:
public class UserDto
{
public string Name { get; set; }
[Sensitive(SensitiveDataType.Phone)]
public string Phone { get; set; }
[Sensitive(SensitiveDataType.IdCard)]
public string IdCard { get; set; }
[Sensitive(SensitiveDataType.Email)]
public string Email { get; set; }
}
在 Program.cs 中注册:
builder.Services.AddSensitiveDataFilter(options =>
{
options.MaxDepth = 5; // 递归扫描最大深度,默认 5
});
使用幂等性验证
[Idempotent]
public async Task<IActionResult> SubmitOrder([FromBody] SubmitOrderRequest request)
{
// 幂等操作
}
使用 RateLimit 声明式限流
[RateLimit] 配合内置 GlobalLimiter 自动生效,无需额外注册。
[RateLimit(By = "User", Limit = 10, WindowSeconds = 60)]
public IActionResult Get() => Ok();
[RateLimit(By = "Tenant", Limit = 100, WindowSeconds = 60)]
public IActionResult List() => Ok();
使用缓存 Attribute(基于 HybridCache)
// 基本用法 — Cache Key: "dict-type:{表达式结果}",HybridCache 自动管理 L1/L2 缓存和击穿保护
[Cacheable("dict-type", Key = "query.Code")]
public async Task<UnifiedResponse> GetDictType(DictTypeQuery query) { }
// 多租户隔离 — Cache Key: "dict-type:{tenantId}:{表达式结果}"
[Cacheable("dict-type", Key = "query.Code", TenantAware = true)]
public async Task<UnifiedResponse> GetDictType(DictTypeQuery query) { }
// 布隆过滤器防穿透 — 缓存键不存在时直接返回,跳过 DB
[Cacheable("dict-type", Key = "query.Code", EnableBloomFilter = true)]
public async Task<UnifiedResponse> GetDictType(DictTypeQuery query) { }
// 缓存清除
[CacheEvict("dict-type", Key = "command.Code", TenantAware = true)]
public async Task<UnifiedResponse> UpdateDictType(UpdateDictTypeCommand command) { }
// 缓存写入
[CachePut("dict-type", Key = "command.Code", TenantAware = true)]
public async Task<UnifiedResponse> CreateDictType(CreateDictTypeCommand command) { }
TenantAware Key 格式
| 场景 | TenantAware | TenantId | Key 示例 |
|---|---|---|---|
| 不感知(默认) | false |
— | dict-type:GZ |
| 感知 + 有租户 | true |
5 | dict-type:5:GZ |
| 感知 + 无租户 | true |
0 | dict-type:global:GZ |
| 感知 + 无 Key 表达式 | true |
5 | dict-type:5 |
前提:使用
TenantAware=true需确保已调用services.AddCore()注册ITenantContext。
权限控制
授权能力由 Galosys.Foundation.AspNetCore.Authorization(ABAC)模块提供——使用方显式调用 AddAuthorizationEngine(),policy 名即策略名(见设计文档 abac-design.md 4.2):
builder.Services.AddAuthorizationEngine(); // 显式装配 ABAC 授权
[Authorize(Policy = "Order.Delete")] // policy 名即策略名
public async Task<IActionResult> DeleteOrder(string orderNo)
{
// 按 ABAC 策略授权
}
SignalR Hub
public class NotificationHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.User(user).SendAsync("ReceiveMessage", message);
}
}
使用多租户(MultiTenancy)
核心基础设施(ITenantContext + ITenantStore 默认 InMemoryTenantStore)由 Core 层注册;AspNetCore 层通过 AddMultiTenancy() 一次注册完整栈:
// Program.cs / Startup.ConfigureServices
builder.Services.AddMultiTenancy() // AddMultiTenancyCore() + 默认 Header 策略 + 访问器 + HttpContextAccessor
.WithHeader() // 默认从请求头 x-tenant-id 解析
.WithHost(); // 追加 Host 解析策略(默认策略已存在时按注册顺序取首个非空)
扩展解析策略
AddMultiTenancy() 返回的构建器提供 5 个追加策略,均可链式组合并反复调用(TryAdd 幂等,已有自定义注册不被覆盖):
// JWT Claim — 从认证用户的声明解析(需在 UseAuthentication 之后使用)
builder.Services.AddMultiTenancy()
.WithJwtClaim(); // 默认声明类型 tenant_id
// .WithJwtClaim("org") // 自定义声明类型
// 路由值 — 从路径参数解析(需在 UseRouting 之后,且路由包含 {tenant} 段)
builder.Services.AddMultiTenancy()
.WithRoute(); // 默认路由键 tenant
// 查询参数 — 从查询字符串解析,如 ?tenant_id=acme
builder.Services.AddMultiTenancy()
.WithQueryString(); // 默认参数名 tenant_id
// .WithQueryString("cid")
// Cookie — 从请求 Cookie 解析
builder.Services.AddMultiTenancy()
.WithCookie(); // 默认 Cookie 名 .tenant_id
// 子域 — 从 Host 子域标签解析
builder.Services.AddMultiTenancy()
.WithSubdomain(); // 默认取首段(SegmentIndex = 0),如 tenant1.galosys.com → tenant1
// .WithSubdomain(segmentIndex: 1, rootDomain: "galosys.com"); // 剥离根域后缀后用第二个标签
建议将
WithJwtClaim与认证中间件顺序配套(UseAuthentication之后注册),将WithRoute与UseRouting之后的端点路由配套;多策略可组合使用(如 Header 优先、Cookie 兜底),由CompositeTenantResolutionStrategy按注册顺序取首个非空结果。
在管道中启用中间件:
app.UseMultiTenancy(); // 遍历已注册的 ITenantResolutionStrategy,命中后设置租户上下文
在控制器 / 业务代码中取当前租户:
var tenant = HttpContext.GetTenant(); // Microsoft.AspNetCore.Http 扩展
// 或使用注入:ITenantContext.Current、ITenantAccessor.Tenant、TenantAccessService.GetTenantAsync(identifier)
使用自定义解析策略或存储(实现 ITenantResolutionStrategy / ITenantStore):
builder.Services.AddMultiTenancy()
.WithResolutionStrategy<JwtClaimResolutionStrategy>() // 自定义策略(transient)
.WithStore<EfCoreTenantStore>(); // 覆写默认 InMemoryTenantStore(singleton,last wins)
详见
docs/adr/0003-multitenancy-isolation-strategies.md(6 项决策)与docs/designs/multi-tenancy-enhancement.md附录 A(四层穿透选型);最小可运行示例见samples/Dev.ConsoleApp/MULTI_TENANCY_SAMPLE.md。
核心类
| 分类 | 类 | 说明 |
|---|---|---|
| Filter | GlobalResponseLoggingResultFilter |
响应日志过滤器 |
| Filter | GlobalLogExceptionFilter |
异常日志过滤器 |
| Filter | AuditLogAttribute |
审计日志特性 |
| Filter | RateLimitAttribute |
声明式限流元数据 |
| Auth | JwtHelper |
JWT 辅助类 |
| Auth | HttpBasicAuthenticationHandler |
HTTP 基本认证 |
| SignalR | HubBase |
Hub 基类 |
| Middleware | GlobalExceptionHandlerMiddleware |
全局异常处理 |
| MultiTenancy | MultiTenancyMiddleware |
多租户中间件(非泛型) |
| MultiTenancy | TenantBuilder |
多租户构建器(WithHeader / WithHost / WithJwtClaim / WithRoute / WithQueryString / WithCookie / WithSubdomain / WithResolutionStrategy / WithStore) |
| MultiTenancy | TenantAccessService |
租户查询服务 |
| MultiTenancy | HeaderResolutionStrategy |
从 HTTP Header 解析租户 |
| MultiTenancy | HostResolutionStrategy |
从 Host 解析租户 |
| MultiTenancy | CompositeTenantResolutionStrategy |
组合式租户解析 |
| MultiTenancy | JwtClaimResolutionStrategy |
从 JWT Claim 解析租户 |
| MultiTenancy | RouteResolutionStrategy |
从路由值解析租户 |
| MultiTenancy | QueryStringResolutionStrategy |
从查询参数解析租户 |
| MultiTenancy | CookieResolutionStrategy |
从 Cookie 解析租户 |
| MultiTenancy | SubdomainResolutionStrategy |
从子域标签解析租户 |
核心类
| 分类 | 类 | 说明 |
|---|---|---|
| Filter | GlobalResponseLoggingResultFilter |
响应日志过滤器 |
| Filter | GlobalLogExceptionFilter |
异常日志过滤器 |
| Filter | AuditLogAttribute |
审计日志特性 |
| Filter | RateLimitAttribute |
声明式限流元数据 |
| Auth | JwtHelper |
JWT 辅助类 |
| Auth | HttpBasicAuthenticationHandler |
HTTP 基本认证 |
| SignalR | HubBase |
Hub 基类 |
| Middleware | GlobalExceptionHandlerMiddleware |
全局异常处理 |
依赖
- Microsoft.AspNetCore.Authentication.JwtBearer
- Microsoft.AspNetCore.SignalR
- Galosys.Foundation.Core
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Galosys.Foundation.Actuator (>= 26.9.3.1)
- Galosys.Foundation.Compliance (>= 26.9.3.1)
- Galosys.Foundation.Core (>= 26.9.3.1)
- microsoft.aspnetcore.authentication.jwtbearer (>= 10.0.0)
- microsoft.extensions.compliance.redaction (>= 10.0.0)
NuGet packages (11)
Showing the top 5 NuGet packages that depend on Galosys.Foundation.AspNetCore:
| Package | Downloads |
|---|---|
|
Galosys.Foundation.AspNetCore.DynamicApi
Galosys.Foundation快速开发库 |
|
|
Galosys.Foundation.AspNetCore.AdminSafe
Galosys.Foundation快速开发库 |
|
|
Galosys.Foundation.AspNetCore.Localization
Galosys.Foundation快速开发库 |
|
|
Galosys.Foundation.AspNetCore.HealthChecks.UI
Galosys.Foundation快速开发库 |
|
|
Galosys.Foundation.AspNetCore.FreeIM
Galosys.Foundation快速开发库 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 26.9.3.1 | 32 | 9/3/2026 |
| 26.8.29.1 | 157 | 8/31/2026 |
| 26.8.26.1 | 187 | 8/26/2026 |
| 26.8.23.1 | 220 | 8/23/2026 |
| 26.8.21.1 | 222 | 8/21/2026 |
| 26.8.20.1 | 221 | 8/20/2026 |
| 26.8.18.1 | 217 | 8/18/2026 |
| 26.8.17.1 | 210 | 8/17/2026 |
| 26.8.13.2 | 193 | 8/13/2026 |
| 26.8.13.1 | 187 | 8/13/2026 |
| 26.8.12.2 | 195 | 8/12/2026 |
| 26.8.12.1 | 196 | 8/12/2026 |
| 26.8.10.1 | 194 | 8/10/2026 |
| 26.8.5.1 | 192 | 8/5/2026 |
| 26.8.4.1 | 201 | 8/4/2026 |
| 26.8.3.1 | 221 | 8/3/2026 |
| 26.7.31.1 | 214 | 7/31/2026 |
| 26.7.30.1 | 218 | 7/30/2026 |
| 26.7.29.1 | 203 | 7/29/2026 |
| 26.7.28.1 | 220 | 7/28/2026 |