Compare commits

...
13 Commits
Author SHA1 Message Date
xrain b534ba9818 gitignore 忽略 .openbitfun 目录 2026-10-06 23:12:52 +08:00
xrain 8d7ba36fb4 新增 ISimApiTokenResolver 自定义Token解析扩展
GetLogin 优先按注册顺序执行 TokenResolver 链, 非null即短路, 全部为null才回退内置缓存; resolver 每次调用在独立作用域内解析并即时释放
2026-10-06 23:12:48 +08:00
xrain e4f051cb61 递归字符串处理 2026-09-04 04:32:52 +08:00
xrain 7b34991ea0 响应log的字符串长度配置 2026-09-04 04:19:03 +08:00
xrain 1623343748 修复了错误 2026-09-04 02:31:33 +08:00
xrain d8a32f3f07 文档相关修复 2026-09-04 02:26:43 +08:00
xrain e17b9d9eed request log add stringfield length 2026-08-11 04:22:36 +08:00
xrain 80a05ea20b 移除了version路由, 融合进config 2026-08-10 22:07:38 +08:00
xrain 33f7cff11c 修复了版本节点错误 2026-08-07 21:45:13 +08:00
xrain c7a4395000 cache/auth 不强依赖Redis 2026-08-07 03:45:19 +08:00
xrain bf98792f96 字典请求返回格式化 2026-07-14 18:59:13 +08:00
xrain 8c5081d442 新增 SimApiRequestLogMiddleware 请求日志中间件,支持配置 ShowFullHeader / ShowFullResponse 2026-07-11 16:15:03 +08:00
xrain 2ed4605a2c PageResponse修正 2026-06-23 17:47:42 +08:00
18 changed files with 851 additions and 115 deletions
+3
View File
@@ -437,3 +437,6 @@ MigrationBackup/
# BitFun snapshot data - auto managed
.bitfun/
/.bitfun/search/flashgrep-index/
.openbitfun/
/.openbitfun/search/flashgrep-index/
+82 -16
View File
@@ -1,39 +1,105 @@
using System;
using System;
using Swashbuckle.AspNetCore.Annotations;
namespace SimApi.Attributes;
/// <summary>
/// 快捷自定义接口文档类
/// 快捷自定义接口文档类(所有参数均可省略, 支持命名参数)。
/// 对应仓颉版 SimApiDoc:
/// tags → 接口标签(逗号分隔, 如 "认证,用户")
/// name → API 名称(映射到 Summary, 作为文档接口标题)
/// description → API 详细描述
/// groupNames → 所属文档组(逗号分隔, 如 "api,admin"; "*" 表示所有文档; null/空 → 仅默认 "api" 文档)
/// ignore → true 时不出现在任何文档中(路由不受影响)
/// 写法示例:
/// [SimApiDoc("认证", "登录")] 位置参数(保持旧版兼容)
/// [SimApiDoc(tags: "认证", name: "登录", description: "...")]
/// [SimApiDoc(groupNames: "api,admin")] 仅指定文档组
/// [SimApiDoc(GroupNames = "*", Ignore = false)] 属性命名参数
/// [SimApiDoc] 全部默认(可标在类上, 仅用 Ignore/GroupNames 等)
/// 属性命名参数优先于构造命名参数。
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class SimApiDocAttribute : SwaggerOperationAttribute
{
/// <summary>
/// 定义接口说明
/// 出现在所有文档组中的通配符
/// </summary>
/// <param name="tags">接口分组列表</param>
public const string AllGroups = "*";
/// <summary>
/// 接口所属的文档组(逗号分隔, 如 "api,admin"); "*" 表示所有文档; null/空 表示未分组(仅默认 "api" 文档)
/// </summary>
public string? GroupNames { get; set; }
/// <summary>
/// 为 true 时该接口不出现在任何文档中(不影响路由)
/// </summary>
public bool Ignore { get; set; }
/// <summary>
/// 定义接口说明(全部可选)
/// </summary>
/// <param name="tags">接口标签, 逗号分隔, 如 "认证,用户"</param>
/// <param name="name">接口名称</param>
/// <param name="description">接口描述</param>
public SimApiDocAttribute(string[] tags, string name, string? description = null)
/// <param name="groupNames">所属文档组, 逗号分隔; "*" 表示所有文档</param>
/// <param name="ignore">true 时不出现在任何文档</param>
public SimApiDocAttribute(string? tags = null, string? name = null, string? description = null,
string? groupNames = null, bool ignore = false)
{
Tags = tags;
Summary = name;
if (description != null)
{
Description = description;
}
// Consumes = new[] {"application/json"};
// Produces = new[] {"application/json"};
Apply(tags, name, description, groupNames, ignore);
}
/// <summary>
/// 定义接口说明
/// 定义接口说明(标签以数组传入)
/// </summary>
/// <param name="tag">接口分组</param>
/// <param name="tags">接口标签列表</param>
/// <param name="name">接口名称</param>
/// <param name="description">接口描述</param>
public SimApiDocAttribute(string tag, string name, string? description = null) : this([tag], name, description)
/// <param name="groupNames">所属文档组, 逗号分隔; "*" 表示所有文档</param>
/// <param name="ignore">true 时不出现在任何文档</param>
public SimApiDocAttribute(string[] tags, string? name = null, string? description = null,
string? groupNames = null, bool ignore = false)
{
Apply(tags, name, description, groupNames, ignore);
}
private void Apply(string? tags, string? name, string? description,
string? groupNames, bool ignore)
{
if (!string.IsNullOrWhiteSpace(tags))
{
Tags = tags.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
}
ApplyCore(name, description, groupNames, ignore);
}
private void Apply(string[] tags, string? name, string? description,
string? groupNames, bool ignore)
{
if (tags is { Length: > 0 })
{
Tags = tags;
}
ApplyCore(name, description, groupNames, ignore);
}
private void ApplyCore(string? name, string? description, string? groupNames, bool ignore)
{
if (!string.IsNullOrEmpty(name))
{
Summary = name;
}
if (!string.IsNullOrEmpty(description))
{
Description = description;
}
GroupNames = groupNames;
Ignore = ignore;
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
/// <typeparam name="T"></typeparam>
public class PageResponse<T>
{
public T? List { get; set; }
public T[] List { get; set; } = [];
public int Page { get; set; } = 1;
public int Count { get; set; } = 20;
public int Total { get; set; }
+13 -2
View File
@@ -6,7 +6,7 @@ namespace SimApi.Configurations;
/// <summary>
/// 文档组配置
/// </summary>
public class SimApiDocGroupOption(string id, string name, string description = "")
public class SimApiDocGroupOption(string id, string name, string description = "", bool isDefault = false)
{
/// <summary>
/// 文档标识
@@ -22,6 +22,11 @@ public class SimApiDocGroupOption(string id, string name, string description = "
/// 文档描述
/// </summary>
public string Description { get; set; } = description!;
/// <summary>
/// 是否为默认文档组: 未标注分组的接口全部归入此文档组
/// </summary>
public bool IsDefault { get; set; } = isDefault;
}
/// <summary>
@@ -50,7 +55,7 @@ public class SimApiDocOptions
/// </summary>
public SimApiDocGroupOption[] ApiGroups { get; set; } =
[
new("api", "Api", "Api接口文档")
new("api", "Api", "Api接口文档", isDefault: true)
];
/// <summary>
@@ -58,6 +63,12 @@ public class SimApiDocOptions
/// </summary>
public SimApiAuthOption ApiAuth { get; set; } = new();
/// <summary>
/// 接口文档页面访问前缀, 默认 "docs"。
/// 访问 /docs 即打开文档页面, JSON 地址为 /docs/{文档组Id}.json
/// </summary>
public string UrlPrefix { get; set; } = "docs";
/// <summary>
/// 文档页面标题
/// </summary>
+33
View File
@@ -1,11 +1,25 @@
using System;
using System.Collections.Generic;
namespace SimApi.Configurations;
public class SimApiOptions
{
/// <summary>
/// Redis配置
/// </summary>
public string? RedisConfiguration { get; set; }
/// <summary>
/// 原样返回给前端的配置信息
/// </summary>
public Dictionary<string, object>? WebConfig { get; set; }
/// <summary>
/// WebConfig返回是否包含版本信息
/// </summary>
public bool WebConfigIncludeVersion { get; set; } = true;
/// <summary>
/// 是否启用后台任务系统 *基于Hangfire
/// </summary>
@@ -17,6 +31,12 @@ public class SimApiOptions
/// </summary>
public bool EnableSimApiAuth { get; set; }
/// <summary>
/// 启用Cache功能
/// </summary>
public bool EnableSimApiCache { get; set; } = true;
/// <summary>
/// 启用SimApi网关授权, 基于上层网关透传的身份令牌验证
/// </summary>
@@ -56,6 +76,12 @@ public class SimApiOptions
/// </summary>
public bool EnableSimApiResponseFilter { get; set; } = true;
/// <summary>
/// 启用请求日志中间件
/// default: false
/// </summary>
public bool EnableRequestLog { get; set; }
/// <summary>
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
/// default: true
@@ -104,6 +130,8 @@ public class SimApiOptions
public SimApiRouteOptions SimApiRouteOptions { get; set; } = new();
public SimApiRequestLogOptions SimApiRequestLogOptions { get; set; } = new();
public void ConfigureSimApiRoute(Action<SimApiRouteOptions>? options = null)
{
options?.Invoke(SimApiRouteOptions);
@@ -143,4 +171,9 @@ public class SimApiOptions
{
options?.Invoke(SimApiAuthCenterOptions);
}
public void ConfigureSimApiRequestLog(Action<SimApiRequestLogOptions>? options = null)
{
options?.Invoke(SimApiRequestLogOptions);
}
}
+24
View File
@@ -0,0 +1,24 @@
namespace SimApi.Configurations;
public class SimApiRequestLogOptions
{
/// <summary>
/// 是否打印完整的请求Header
/// </summary>
public bool ShowFullHeader { get; set; }
/// <summary>
/// 是否打印完整的响应体
/// </summary>
public bool ShowFullResponse { get; set; }
/// <summary>
/// 请求字段显示最长长度
/// </summary>
public int RequestStringLogLength { get; set; } = 0;
/// <summary>
/// 响应字段显示最长长度
/// </summary>
public int ResponseStringLogLength { get; set; } = 0;
}
+1 -1
View File
@@ -2,7 +2,7 @@
public class SimApiRouteOptions
{
public string? VersionRoute = "/versions";
public string? LogoutRoute = "/auth/logout";
public string? UserInfoRoute = "/user/info";
public string? WebConfigRoute = "/config";
}
+1 -1
View File
@@ -11,7 +11,7 @@ public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
/// 退出登陆
/// </summary>
/// <returns></returns>
[HttpPost, SimApiDoc("认证", "退出登陆")]
[HttpPost, SimApiDoc("认证", "退出登陆",groupNames: "*")]
public void Logout()
{
if (Request.Headers.TryGetValue("Token", out var value))
+48
View File
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using SimApi.Configurations;
namespace SimApi.Controllers;
/// <summary>
/// SimApi 内置端点路由表中的一项。
/// </summary>
public sealed record SimApiBuiltInRoute(
string RouteName,
string Controller,
string Action,
string[] HttpMethods,
string Path);
/// <summary>
/// SimApi 内置端点路由表 —— 路径的唯一配置处。
/// UseSimApi 用它注册约定路由(动态路由),
/// SimApiBuiltInRoutesDescriptionProvider 用它生成文档条目。
/// 某项路径为 null / 空时该端点既不注册路由、也不出现在文档中。
/// </summary>
public static class SimApiBuiltInRoutes
{
public static IEnumerable<SimApiBuiltInRoute> Get(SimApiRouteOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (!string.IsNullOrEmpty(options.UserInfoRoute))
{
yield return new SimApiBuiltInRoute(
"UserInfo", "SimApiCommon", "UserInfo", ["POST"], options.UserInfoRoute);
}
if (!string.IsNullOrEmpty(options.LogoutRoute))
{
yield return new SimApiBuiltInRoute(
"Logout", "SimApiAuth", "Logout", ["POST"], options.LogoutRoute);
}
if (!string.IsNullOrEmpty(options.WebConfigRoute))
{
// 控制器动作同时标注了 HttpGet/HttpPost
yield return new SimApiBuiltInRoute(
"WebConfig", "SimApiCommon", "WebConfig", ["GET", "POST"], options.WebConfigRoute);
}
}
}
@@ -0,0 +1,117 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using SimApi.Configurations;
namespace SimApi.Controllers;
/// <summary>
/// 将 SimApiRouteOptions 动态配置的内置约定路由(UserInfo / Logout / WebConfig)
/// 翻译成 ApiDescription, 使它们能像属性路由接口一样出现在 Swagger 文档中:
/// 请求/响应 schema 由 Swashbuckle 自动分析, 方法上已有的 [SimApiDoc] 注解自动生效。
/// 路径为 null / 空 的端点在此一并跳过(与路由注册保持一致)。
/// </summary>
public class SimApiBuiltInRoutesDescriptionProvider(
IServiceProvider services,
SimApiOptions options) : IApiDescriptionProvider
{
/// <summary>
/// 默认 provider(DefaultApiDescriptionProvider)的 Order 为 -1000, 位于其后执行。
/// </summary>
public int Order => -900;
public void OnProvidersExecuting(ApiDescriptionProviderContext context)
{
}
public void OnProvidersExecuted(ApiDescriptionProviderContext context)
{
var modelMetadata = services.GetService<IModelMetadataProvider>();
foreach (var route in SimApiBuiltInRoutes.Get(options.SimApiRouteOptions))
{
var action = context.Actions.OfType<ControllerActionDescriptor>()
.FirstOrDefault(a =>
string.Equals(a.ControllerName, route.Controller, StringComparison.Ordinal) &&
string.Equals(a.ActionName, route.Action, StringComparison.Ordinal));
if (action is null)
{
continue;
}
// 若该动作已被属性路由 / 其他 provider 收录, 跳过避免重复
if (context.Results.Any(d => ReferenceEquals(d.ActionDescriptor, action)))
{
continue;
}
foreach (var httpMethod in route.HttpMethods)
{
context.Results.Add(CreateDescription(action, route, httpMethod, modelMetadata));
}
}
}
private static ApiDescription CreateDescription(
ControllerActionDescriptor action,
SimApiBuiltInRoute route,
string httpMethod,
IModelMetadataProvider? modelMetadata)
{
var apiDescription = new ApiDescription
{
ActionDescriptor = action,
HttpMethod = httpMethod,
RelativePath = route.Path.TrimStart('/')
};
// 输入: 按真实方法参数翻译(内置端点均为零参, 此处保证将来加参也可分析)
foreach (var parameter in action.Parameters)
{
var parameterDescription = new ApiParameterDescription
{
Name = parameter.Name,
Type = parameter.ParameterType,
ParameterDescriptor = parameter,
Source = parameter.BindingInfo?.BindingSource ?? BindingSource.Body,
IsRequired = true
};
if (modelMetadata is not null)
{
parameterDescription.ModelMetadata = modelMetadata.GetMetadataForType(parameter.ParameterType);
}
apiDescription.ParameterDescriptions.Add(parameterDescription);
}
// 输出: 方法返回类型 => 200 + json
var returnType = Unwrap(action.MethodInfo.ReturnType);
if (returnType != typeof(void))
{
var responseType = new ApiResponseType
{
StatusCode = 200,
Type = returnType,
IsDefaultResponse = true
};
if (modelMetadata is not null)
{
responseType.ModelMetadata = modelMetadata.GetMetadataForType(returnType);
}
responseType.ApiResponseFormats.Add(new ApiResponseFormat { MediaType = "application/json" });
apiDescription.SupportedResponseTypes.Add(responseType);
}
return apiDescription;
}
private static Type Unwrap(Type type) =>
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Task<>)
? type.GetGenericArguments()[0]
: type;
}
+22 -9
View File
@@ -1,13 +1,16 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Helpers;
using static SimApi.Helpers.SimApiError;
namespace SimApi.Controllers;
public class SimApiCommonController : SimApiBaseController
public class SimApiCommonController(SimApiOptions simApiOptions) : SimApiBaseController
{
/// <summary>
/// 错误回馈页面
@@ -15,21 +18,31 @@ public class SimApiCommonController : SimApiBaseController
/// <param name="code">错误代码</param>
/// <returns></returns>
[HttpGet("exception/{code:int}")]
[ApiExplorerSettings(IgnoreApi = true)]
[SimApiDoc(ignore: true)]
public void ExceptionHandler(int code)
{
Error(code);
}
/// <summary>
/// 给前端的自定义信息
/// </summary>
/// <returns></returns>
[HttpPost, HttpGet]
public Dictionary<string, string> Versions()
[HttpPost, SimApiDoc("公共", "获取自定义配置",groupNames: "*")]
public Dictionary<string, object> WebConfig()
{
return new Dictionary<string, string>
var resp = simApiOptions.WebConfig!.ToDictionary();
if (simApiOptions.WebConfigIncludeVersion)
{
{ "SimApi", SimApiUtil.SimApiVersion },
{ "App", SimApiUtil.AppVersion }
};
resp.Add("Versions", new Dictionary<string, string>
{
{ "SimApi", SimApiUtil.SimApiVersion },
{ "App", SimApiUtil.AppVersion }
});
}
return resp;
}
@@ -37,6 +50,6 @@ public class SimApiCommonController : SimApiBaseController
/// 获取已登录用户信息
/// </summary>
/// <returns></returns>
[HttpPost, SimApiAuth, SimApiDoc("认证", "获取已登录用户信息")]
[HttpPost, SimApiAuth, SimApiDoc("认证", "获取已登录用户信息",groupNames: "*")]
public SimApiLoginItem UserInfo() => LoginInfo;
}
+118 -42
View File
@@ -1,19 +1,36 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using SimApi.Communications;
using SimApi.Interfaces;
using StackExchange.Redis;
namespace SimApi.Helpers;
/// <summary>
/// 认证助手
/// 认证助手(支持 Redis 和 InMemory 两种模式)
/// </summary>
public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
public class SimApiAuth
{
private const string TokenCacheKey = "SimApi:Auth:Token:{token}";
private const string TokenSetCacheKey = "SimApi:Auth:User:{userId}";
private readonly IDatabase _redisDb = redis.GetDatabase();
private readonly IDistributedCache _cache;
private readonly IDatabase? _redisDb;
private readonly IServiceScopeFactory _scopeFactory;
// InMemory 模式:用户 → Token集合
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _userTokens = new();
public SimApiAuth(IDistributedCache cache, IServiceProvider sp, IServiceScopeFactory scopeFactory)
{
_cache = cache;
_redisDb = sp.GetService<IConnectionMultiplexer>()?.GetDatabase();
_scopeFactory = scopeFactory;
}
/// <summary>
/// 登录信息
@@ -28,13 +45,20 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
token ??= Guid.NewGuid().ToString();
var cacheKey = TokenCacheKey.Replace("{token}", token);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.SetAdd(setCacheKey, token);
cache.SetString(cacheKey, SimApiUtil.Json(loginItem),
new DistributedCacheEntryOptions
{
SlidingExpiration = expireTime
});
_redisDb.KeyExpire(setCacheKey, expireTime.Value);
_cache.SetString(cacheKey, SimApiUtil.Json(loginItem),
new DistributedCacheEntryOptions { SlidingExpiration = expireTime });
if (_redisDb != null)
{
_redisDb.SetAdd(setCacheKey, token);
_redisDb.KeyExpire(setCacheKey, expireTime.Value);
}
else
{
var tokens = _userTokens.GetOrAdd(loginItem.Id, _ => new ConcurrentDictionary<string, byte>());
tokens.TryAdd(token, 0);
}
return token;
}
@@ -48,10 +72,15 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
public string Update(SimApiLoginItem loginItem, string token)
{
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.SetString(cacheKey, SimApiUtil.Json(loginItem));
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.KeyExpire(setCacheKey, ttl);
_cache.SetString(cacheKey, SimApiUtil.Json(loginItem));
if (_redisDb != null)
{
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.KeyExpire(setCacheKey, ttl);
}
return token;
}
@@ -63,10 +92,18 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
/// <returns></returns>
public SimApiLoginItem? GetLogin(string token)
{
using var scope = _scopeFactory.CreateScope(); // 用完即释放
foreach (var resolver in scope.ServiceProvider.GetServices<ISimApiTokenResolver>())
{
var item = resolver.Run(token);
if (item != null) return item;
}
var cacheKey = TokenCacheKey.Replace("{token}", token);
var login = cache.GetString(cacheKey);
var login = _cache.GetString(cacheKey);
var resp = login != null ? SimApiUtil.FromJson<SimApiLoginItem>(login) : null;
if (resp != null)
if (resp != null && _redisDb != null)
{
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", resp.Id);
@@ -83,26 +120,42 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
/// <returns></returns>
public SimApiLoginItem[] GetAllLogins(string userId)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
var resp = new List<SimApiLoginItem>();
foreach (var login in allLogins)
if (_redisDb != null)
{
if (login != null)
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
var resp = new List<SimApiLoginItem>();
foreach (var login in allLogins)
{
var item = GetLogin(login);
if (item != null)
if (login != null)
{
resp.Add(item);
}
else
{
_redisDb.SetRemove(setCacheKey, login);
var item = GetLogin(login);
if (item != null)
resp.Add(item);
else
_redisDb.SetRemove(setCacheKey, login);
}
}
}
return resp.ToArray();
return resp.ToArray();
}
else
{
if (!_userTokens.TryGetValue(userId, out var tokens))
return [];
var resp = new List<SimApiLoginItem>();
foreach (var token in tokens.Keys)
{
var item = GetLogin(token);
if (item != null)
resp.Add(item);
else
tokens.TryRemove(token, out _);
}
return resp.ToArray();
}
}
/// <summary>
@@ -111,18 +164,32 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
/// <param name="userId"></param>
public void LogoutAll(string userId)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
foreach (var login in allLogins)
if (_redisDb != null)
{
if (login != null)
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
foreach (var login in allLogins)
{
var cacheKey = TokenCacheKey.Replace("{token}", login);
cache.Remove(cacheKey);
if (login != null)
{
var cacheKey = TokenCacheKey.Replace("{token}", login);
_cache.Remove(cacheKey);
}
}
_redisDb.KeyDelete(setCacheKey);
}
else
{
if (_userTokens.TryRemove(userId, out var tokens))
{
foreach (var token in tokens.Keys)
{
var cacheKey = TokenCacheKey.Replace("{token}", token);
_cache.Remove(cacheKey);
}
}
}
_redisDb.KeyDelete(setCacheKey);
}
/// <summary>
@@ -132,13 +199,22 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
public void Logout(string token)
{
var item = GetLogin(token);
if (item != null)
if (_redisDb != null)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", item.Id);
_redisDb.SetRemove(setCacheKey, token);
if (item != null)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", item.Id);
_redisDb.SetRemove(setCacheKey, token);
}
}
else
{
if (item != null && _userTokens.TryGetValue(item.Id, out var tokens))
tokens.TryRemove(token, out _);
}
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.Remove(cacheKey);
_cache.Remove(cacheKey);
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ public static class SimApiUtil
{
// ReferenceHandler = ReferenceHandler.Preserve,
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
// DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
+31
View File
@@ -0,0 +1,31 @@
using SimApi.Communications;
namespace SimApi.Interfaces;
/// <summary>
/// 自定义 Token 解析扩展点,用于让 <c>SimApiAuth.GetLogin</c> 识别本库之外签发的 Token(JWT、第三方登录态等)。
/// </summary>
/// <remarks>
/// <b>注册</b>:本库不会自动发现实现,必须由使用者自行注册。<c>AddScoped</c> / <c>AddSingleton</c> / <c>AddTransient</c>
/// 均可,因为每次调用都在独立作用域内解析。仅在 <c>EnableSimApiAuth = true</c> 时才会被执行。<br/>
/// <b>调用时机</b>:每次 <c>GetLogin</c>(即每个携带 Token 的请求)都会先执行全部 resolver,再回退到内置缓存查询;
/// 因此本机 <c>Login</c> 签发的 Token 同样会走一遍 resolver 链。<c>Logout</c> 与 <c>GetAllLogins</c> 内部也调用
/// <c>GetLogin</c>,同样会触发 resolver 链,其中 <c>GetAllLogins</c> 会按该用户的 Token 数量执行多次。<br/>
/// <b>顺序</b>:按注册顺序依次执行,返回非 <c>null</c> 即作为认证结果并立即短路,后续 resolver 与内置缓存不再参与。<br/>
/// <b>生命周期</b>:每次调用在根容器新建的子作用域内解析,因此可以安全注入 Scoped 服务(如 DbContext)。
/// 但该作用域不是当前请求的作用域,请求级事务 / UnitOfWork 的未提交改动不可见,实现应当只读。<br/>
/// <b>返回值</b>:必须是完全物化的对象。作用域在返回后立即释放,不可返回依赖延迟加载的 EF 追踪实体。<br/>
/// <b>Token 管理</b>:返回的登录态不受本库管理,<c>Login</c> / <c>Update</c> / <c>GetAllLogins</c> 不会包含它,
/// <c>Logout</c> 对它无效,吊销需由实现方自行处理。<br/>
/// <b>异常</b>:抛出的异常会直接冒泡并中断整条链(该请求认证失败)。表示“不是我的 Token”请返回 <c>null</c>,不要抛异常。<br/>
/// <b>性能</b>:这是认证热路径上的同步方法,查库等 I/O 会阻塞调用线程,建议在实现内部自行做短 TTL 缓存。
/// </remarks>
public interface ISimApiTokenResolver
{
/// <summary>
/// 尝试解析 Token。
/// </summary>
/// <param name="token">请求携带的 Token 原文。</param>
/// <returns>解析成功返回登录信息;不属于本实现的 Token 返回 <c>null</c> 由后续 resolver 继续处理。</returns>
public SimApiLoginItem? Run(string token);
}
+196
View File
@@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SimApi.Configurations;
using SimApi.Helpers;
namespace SimApi.Middlewares;
/// <summary>
/// 请求日志中间件
/// </summary>
public class SimApiRequestLogMiddleware(
RequestDelegate next,
ILogger<SimApiRequestLogMiddleware> log,
SimApiRequestLogOptions options)
{
public async Task InvokeAsync(HttpContext context)
{
var sw = Stopwatch.StartNew();
var fullUrl =
$"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
var logMessage = new StringBuilder();
logMessage.AppendLine($"[{context.Request.Method}] {fullUrl}");
if (options.ShowFullHeader)
{
logMessage.AppendLine("*( RequestHeaders [Full] ) =>");
var headersDict = new Dictionary<string, string>();
foreach (var header in context.Request.Headers)
{
headersDict[header.Key] = header.Value.ToString();
}
logMessage.AppendLine(JsonSerializer.Serialize(headersDict));
}
else
{
logMessage.AppendLine("*( RequestHeaders ) =>");
var token = context.Request.Headers["Token"].FirstOrDefault() ?? "";
var queryId = context.Request.Headers["Query-Id"].FirstOrDefault() ?? "";
logMessage.AppendLine($"Token: {token} QueryId: {queryId}");
}
context.Request.EnableBuffering();
var requestBodyText = await new StreamReader(context.Request.Body).ReadToEndAsync();
context.Request.Body.Seek(0, SeekOrigin.Begin);
logMessage.AppendLine("*( RequestBody ) =>");
if (options.RequestStringLogLength == 0)
{
logMessage.AppendLine(requestBodyText);
}
else
{
// GET/DELETE 等无 body 的请求, 或表单/文件上传等非 JSON body:
// 不做长度裁剪, 原样记录, 避免空 JSON 解析抛异常
logMessage.AppendLine(TrimJsonStringFields(requestBodyText, options.RequestStringLogLength));
}
var originalBodyStream = context.Response.Body;
using var responseBody = new MemoryStream();
context.Response.Body = responseBody;
ExceptionDispatchInfo? edi = null;
try
{
await next(context);
}
catch (Exception ex)
{
edi = ExceptionDispatchInfo.Capture(ex);
}
finally
{
sw.Stop();
responseBody.Seek(0, SeekOrigin.Begin);
var responseText = await new StreamReader(responseBody).ReadToEndAsync();
logMessage.AppendLine($"*( Response [{context.Response.StatusCode}] ) =>");
if (options.ResponseStringLogLength > 0)
{
// 与请求体相同的字段级裁剪: JSON 按字段截断超长字符串, 非 JSON/空响应原样记录
logMessage.Append(TrimJsonStringFields(responseText, options.ResponseStringLogLength));
}
else if (options.ShowFullResponse)
{
logMessage.Append(responseText);
}
else
{
var truncated = responseText.Length > 200 ? responseText[..200] : responseText;
logMessage.Append(truncated);
}
if (edi != null)
{
logMessage.Append(Environment.NewLine);
logMessage.Append($"Exception: {edi.SourceException}");
}
responseBody.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
context.Response.Body = originalBodyStream;
log.LogInformation(logMessage.ToString());
}
edi?.Throw();
}
/// <summary>
/// 与请求体相同的字段级裁剪(递归):
/// 遍历 JSON 对象/数组的所有层级, 把长度超过 maxLength 的字符串字段截断为前 maxLength 字符并追加 ...(原长度);
/// 空 body 或非 JSON body(表单/文件上传等)原样返回, 不裁剪
/// </summary>
private static string TrimJsonStringFields(string text, int maxLength)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
JsonNode? root;
try
{
root = JsonNode.Parse(text);
}
catch (JsonException)
{
return text;
}
if (root == null)
{
return text;
}
TrimNode(root, maxLength);
return SimApiUtil.Json(root);
}
/// <summary>
/// 递归裁剪节点下所有层级的字符串值:
/// 纯字符串字面量超长时截断, 数字/布尔/嵌套对象/数组继续向下递归
/// </summary>
private static void TrimNode(JsonNode? node, int maxLength)
{
switch (node)
{
case JsonObject obj:
// 键快照遍历后再赋值, 避免枚举过程中修改集合引发异常
foreach (var prop in obj.ToList())
{
if (prop.Value is JsonValue value &&
value.TryGetValue<string>(out var str) &&
str.Length > maxLength)
{
obj[prop.Key] = JsonValue.Create(str[..maxLength] + $"...({str.Length})");
}
else
{
TrimNode(prop.Value, maxLength);
}
}
break;
case JsonArray arr:
for (var i = 0; i < arr.Count; i++)
{
if (arr[i] is JsonValue value &&
value.TryGetValue<string>(out var str) &&
str.Length > maxLength)
{
arr[i] = JsonValue.Create(str[..maxLength] + $"...({str.Length})");
}
else
{
TrimNode(arr[i], maxLength);
}
}
break;
}
}
}
+54 -3
View File
@@ -13,6 +13,7 @@ ASP.NET Core API 基础框架库,提供统一异常拦截、响应封装、Tok
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSimApi(options =>
{
// RedisConfiguration 可选:配置则使用 Redis,不配则自动使用 InMemory
options.RedisConfiguration = "localhost:6379";
options.EnableSimApiAuth = true;
options.EnableSimApiDoc = true;
@@ -77,7 +78,7 @@ SimApi/
├── Configurations/ # SimApiOptions + 各模块 Option 类
├── Controllers/ # SimApiBaseController, SimApiCommonController, SimApiAuthController
├── Helpers/ # SimApiError, SimApiAuth, SimApiCache, SimApiHttpClient, SimApiStorage, SimApiUtil, SimApiAesUtil
├── Interfaces/ # ISimApiAuthChecker
├── Interfaces/ # ISimApiAuthChecker, ISimApiTokenResolver
├── Middlewares/ # SimApiExceptionMiddleware, SimApiAuthMiddleware
├── Synapse/ # MQTT Pub/Sub + RPC + Config Store
├── Exceptions/ # SimApiException
@@ -191,6 +192,26 @@ public class SimApiLoginItem {
**Token 传参**: Header `Token: <value>`
### 存储模式
`SimApiAuth` 内部自动判断,无需手动配置:
| 条件 | 存储后端 | 用户↔Token 映射 |
|------|---------|-----------------|
| 配置了 `RedisConfiguration` | Redis(`IDistributedCache` + Set) | Redis Set |
| 未配置 `RedisConfiguration` | InMemory(`DistributedMemoryCache`) | `ConcurrentDictionary` |
- **Redis 模式**:支持多实例共享,Token 持久化,适合生产环境
- **InMemory 模式**:零配置即可启用 `EnableSimApiAuth`,适合开发/测试/单实例场景。注意重启后所有登录态丢失
```csharp
// 不配 Redis 也能用 Auth
builder.Services.AddSimApi(options =>
{
options.EnableSimApiAuth = true; // 自动使用 InMemory
});
```
### 认证后处理 Hook — ISimApiAuthChecker
```csharp
@@ -200,6 +221,33 @@ public interface ISimApiAuthChecker {
// 实现后自动注册为 Scoped,每次认证后调用
```
### 自定义 Token 解析 — ISimApiTokenResolver
让认证识别**本库之外签发的 Token**(JWT、第三方登录态等),是 `GetLogin` 的前置扩展点。
```csharp
public interface ISimApiTokenResolver {
SimApiLoginItem? Run(string token); // 不是自己负责的 Token 返回 null
}
```
**必须由使用者手动注册**,本库不会自动发现实现(`AddScoped` / `AddSingleton` / `AddTransient` 均可):
```csharp
builder.Services.AddScoped<ISimApiTokenResolver, MyJwtTokenResolver>();
```
调用行为:
- 每次 `GetLogin`(即每个携带 Token 的请求)都会**先**按注册顺序执行全部 resolver,返回非 `null` 即短路生效;全部返回 `null` 才回退到内置缓存查询
- 因此本机 `Login()` 签发的 Token 同样会走一遍 resolver 链,实现应保持廉价,或自行做短 TTL 缓存
- `Logout` 与 `GetAllLogins` 内部也会调用 `GetLogin`,同样会触发 resolver 链,其中 `GetAllLogins` 会按该用户的 Token 数量执行多次
- 每次调用在新建的子作用域内解析,可以注入 Scoped 服务(如 `DbContext`);但它**不是当前请求的作用域**,请求级事务 / UnitOfWork 的未提交改动不可见,实现应当只读
- 返回值必须是完全物化的对象,作用域在返回后立即释放,不可返回依赖延迟加载的 EF 追踪实体
- 返回的登录态**不受本库管理**:`Login` / `Update` / `GetAllLogins` 不会包含它,`Logout` 对它无效,吊销需由实现方自行处理
- 抛出的异常会中断整条链并导致该请求认证失败;表示"不是我的 Token"请返回 `null`,不要抛异常
- 仅在 `EnableSimApiAuth = true` 时才会被执行
---
## 4. AuthSDK — Auth Center 网关 & IAM
@@ -406,9 +454,11 @@ IMinioClient Client { get; } // 底层 MinIO 客户端
---
## 8. Redis 缓存 — SimApiCache
## 8. 缓存 — SimApiCache
依赖 `RedisConfiguration`,Key 自动加前缀 `SimApi:Cache:`。
通过 `EnableSimApiCache`(默认 `true`)控制。Key 自动加前缀 `SimApi:Cache:`。
存储后端与 `SimApiAuth` 一致:配了 `RedisConfiguration` 就用 Redis,否则用 InMemory。
```csharp
void Set(string key, object value, DistributedCacheEntryOptions? options = null);
@@ -617,6 +667,7 @@ builder.Services.AddSimApi(options =>
// 功能开关
options.EnableSimApiAuth = false; // Token 认证
options.EnableSimApiCache = true; // 缓存(Redis 或 InMemory)
options.EnableSimApiAuthGate = false; // Auth Center 网关鉴权
options.EnableSimApiDoc = false; // Swagger 文档
options.EnableSimApiStorage = false; // S3 存储
+78 -35
View File
@@ -9,15 +9,18 @@ using Hangfire.Redis.StackExchange;
using SimApi.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi;
using SimApi.Middlewares;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SimApi.Attributes;
using SimApi.AuthSDK;
using SimApi.Configurations;
using SimApi.Controllers;
using SimApi.Interfaces;
using SimApi.Logger;
using SimApi.SwaggerFilters;
@@ -36,11 +39,22 @@ public static class SimApiExtensions
{
var simApiOptions = new SimApiOptions();
options?.Invoke(simApiOptions);
simApiOptions.WebConfig ??= new();
builder.AddSingleton(simApiOptions);
if (simApiOptions.RedisConfiguration != null)
{
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
builder.AddSingleton<IConnectionMultiplexer>(_ =>
ConnectionMultiplexer.Connect(simApiOptions.RedisConfiguration));
}
else if (simApiOptions.EnableSimApiAuth || simApiOptions.EnableSimApiCache)
{
builder.AddDistributedMemoryCache();
}
if (simApiOptions.EnableSimApiCache)
{
builder.AddSingleton<SimApiCache>();
}
@@ -209,6 +223,7 @@ public static class SimApiExtensions
x.OperationFilter<SimApiSignOperationFilter>();
x.OperationFilter<AesBodyOperationFilter>();
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
x.SchemaFilter<DictionarySchemaFilter>();
x.DocumentFilter<RemoveEmptyTagsFilter>();
if (simApiOptions.EnableSimApiAuth)
{
@@ -217,15 +232,42 @@ public static class SimApiExtensions
x.DocInclusionPredicate((docName, apiDesc) =>
{
// 获取接口标记的 GroupName(未标记则为 null)
var actionGroupName = apiDesc.ActionDescriptor.EndpointMetadata
var metadata = apiDesc.ActionDescriptor.EndpointMetadata;
// 类/方法上的 [SimApiDoc] 标注统一控制文档归属
var docAttrs = metadata.OfType<SimApiDocAttribute>().ToArray();
// Ignore: 不出现在任何文档(路由不受影响)
if (docAttrs.Any(a => a.Ignore))
{
return false;
}
// GroupNames: 逗号分隔的文档组列表; "*" 表示所有文档;
// 标注在类上则整类生效, 方法级标注可覆盖
var groupNames = docAttrs
.Select(a => a.GroupNames)
.FirstOrDefault(g => !string.IsNullOrWhiteSpace(g));
if (groupNames != null)
{
var groups = groupNames.Split(',',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
return groups.Contains(SimApiDocAttribute.AllGroups) || groups.Contains(docName);
}
// 兼容: ApiExplorerSettings.GroupName 单组标注
var actionGroupName = metadata
.OfType<ApiExplorerSettingsAttribute>()
.FirstOrDefault()?.GroupName;
// 情况1:接口未标记任何 GroupName(actionGroupName 为 null)
// 未标注任何分组 → 放入配置为 IsDefault 的文档组;
// 未配置 IsDefault 时依次回退 id 为 "api" 的组 / 第一个组
if (actionGroupName == null)
{
return docName == "api"; // 未分组接口只属于默认分组v1
var defaultGroup = docOptions.ApiGroups.FirstOrDefault(g => g.IsDefault)
?? docOptions.ApiGroups.FirstOrDefault(g => g.Id == "api")
?? docOptions.ApiGroups.FirstOrDefault();
return defaultGroup != null && docName == defaultGroup.Id;
}
return docName == actionGroupName;
@@ -296,6 +338,13 @@ public static class SimApiExtensions
});
}
});
// 让 SimApiRouteOptions 配置的内置约定路由(UserInfo/Logout/WebConfig)
// 也能出现在文档中: 通过 IApiDescriptionProvider 手工产出 ApiDescription,
// 请求/响应 schema 由 Swashbuckle 自动分析, [SimApiDoc] 注解自动生效。
builder.TryAddEnumerable(
ServiceDescriptor.Transient<IApiDescriptionProvider,
SimApiBuiltInRoutesDescriptionProvider>());
}
// 使用Header转发,应对代理后获取真实ip
@@ -305,7 +354,6 @@ public static class SimApiExtensions
{
fwOptions.ForwardedHeaders = ForwardedHeaders.All;
fwOptions.KnownNetworks.Clear();
fwOptions.KnownProxies.Clear();
});
}
@@ -339,7 +387,7 @@ public static class SimApiExtensions
}
}
builder.AddSingleton(simApiOptions);
builder.AddSingleton(simApiOptions.SimApiRequestLogOptions);
return builder;
}
@@ -358,6 +406,11 @@ public static class SimApiExtensions
logger.LogInformation("开始配置 RedisCache ...");
}
if (options.EnableSimApiCache)
{
logger.LogInformation("开始配置SimApiCache...");
}
//请求一下检测存储错误
if (options.EnableSimApiStorage)
{
@@ -445,37 +498,19 @@ public static class SimApiExtensions
builder.UseMiddleware<SimApiAuthMiddleware>();
}
if (options.SimApiRouteOptions.VersionRoute != null)
// 注册内置Route(UserInfo/Logout/WebConfig)。
// 路径统一由 SimApiBuiltInRoutes 路由表提供: 配置为 null/空 的端点不注册。
foreach (var route in SimApiBuiltInRoutes.Get(options.SimApiRouteOptions))
{
logger.LogInformation("注册内置Route: Versions => {}", options.SimApiRouteOptions.LogoutRoute);
builder.MapControllerRoute(name: "Versions", pattern: options.SimApiRouteOptions.VersionRoute,
logger.LogInformation("注册内置Route: {RouteName} => {RoutePath} [{HttpMethods}]", route.RouteName,
route.Path, string.Join(", ", route.HttpMethods));
builder.MapControllerRoute(
name: route.RouteName,
pattern: route.Path,
defaults: new
{
controller = "SimApiCommon",
action = "Versions"
});
}
if (options.SimApiRouteOptions.UserInfoRoute != null)
{
logger.LogInformation("注册内置Route: UserInfo => {}", options.SimApiRouteOptions.UserInfoRoute);
builder.MapControllerRoute(name: "UserInfo", pattern: options.SimApiRouteOptions.UserInfoRoute,
defaults: new
{
controller = "SimApiCommon",
action = "UserInfo"
});
}
if (options.SimApiRouteOptions.LogoutRoute != null)
{
logger.LogInformation("注册内置Route: Logout => {}", options.SimApiRouteOptions.LogoutRoute);
builder.MapControllerRoute(name: "Logout", pattern: options.SimApiRouteOptions.LogoutRoute,
defaults: new
{
controller = "SimApiAuth",
action = "Logout"
controller = route.Controller,
action = route.Action
});
}
@@ -483,12 +518,14 @@ public static class SimApiExtensions
{
logger.LogInformation("开始配置SimApiDoc...");
var docOptions = options.SimApiDocOptions;
builder.UseSwagger(x => x.RouteTemplate = "/swagger/{documentName}.json")
builder.UseSwagger(x => x.RouteTemplate = $"/{docOptions.UrlPrefix}/{{documentName}}.json")
.UseSwaggerUI(x =>
{
x.RoutePrefix = docOptions.UrlPrefix;
x.DocumentTitle = docOptions.DocumentTitle;
foreach (var group in docOptions.ApiGroups)
{
// 相对端点: 页面位于 /{UrlPrefix}/, 自动解析为 /{UrlPrefix}/{group.Id}.json
x.SwaggerEndpoint($"{group.Id}.json", name: group.Name);
}
@@ -497,6 +534,12 @@ public static class SimApiExtensions
});
}
if (options.EnableRequestLog)
{
logger.LogInformation("开始配置SimApiRequestLog...");
builder.UseMiddleware<SimApiRequestLogMiddleware>();
}
if (options.EnableSimApiException)
{
logger.LogInformation("开始配置SimApiException...");
+24
View File
@@ -0,0 +1,24 @@
using System.Collections.Generic;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace SimApi.SwaggerFilters;
public class DictionarySchemaFilter : ISchemaFilter
{
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
{
if (!context.Type.IsGenericType || context.Type.GetGenericTypeDefinition() != typeof(Dictionary<,>))
return;
if (schema is not OpenApiSchema concrete) return;
var valueType = context.Type.GetGenericArguments()[1];
concrete.Type = JsonSchemaType.Object;
concrete.AdditionalPropertiesAllowed = true;
concrete.AdditionalProperties = context.SchemaGenerator.GenerateSchema(valueType, context.SchemaRepository);
concrete.Properties?.Clear();
concrete.Example = null;
concrete.Examples?.Clear();
}
}