Compare commits

...
17 Commits
24 changed files with 1606 additions and 96 deletions
+3 -3
View File
@@ -10,11 +10,11 @@ jobs:
name: Publish Project to Nuget
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v4
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v5
with:
dotnet-version: "9.0.305"
dotnet-version: "10.x.x"
- name: Publish
run: |
version=`git describe --tags`
+20
View File
@@ -0,0 +1,20 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using SimApi.ModelBinders;
namespace SimApi.Attributes;
[AttributeUsage(AttributeTargets.Parameter)]
public class AesBodyAttribute : ModelBinderAttribute
{
public Type KeyProvider { get; set; } = typeof(AesBodyProviderBase);
public override BindingSource BindingSource => BindingSource.Body;
public AesBodyAttribute()
{
// 指定使用自定义的模型绑定器
BinderType = typeof(AesBodyModelBinder);
Name = KeyProvider.FullName;
}
}
+4 -9
View File
@@ -13,13 +13,13 @@ namespace SimApi.Attributes;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SimApiAuthAttribute : ActionFilterAttribute
{
private string[] Types { get; }
private string[]? Types { get; }
//默认是user登录类型
public SimApiAuthAttribute()
{
Types = new[] { "user" };
Types = null;
}
//只检测一种用户类型的快捷方式
@@ -34,13 +34,6 @@ public class SimApiAuthAttribute : ActionFilterAttribute
Types = types;
}
//只检测一种用户类型的快捷方式
public SimApiAuthAttribute(string type, string url)
{
Types = new[] { type };
new HttpPostAttribute(url);
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
@@ -49,6 +42,8 @@ public class SimApiAuthAttribute : ActionFilterAttribute
{
throw new SimApiException(401);
}
if (Types == null) return;
//检测用户类型
if (!Types.Intersect(loginInfo.Type).Any())
{
+6 -1
View File
@@ -14,10 +14,15 @@ public class SimApiDocAttribute : SwaggerOperationAttribute
/// </summary>
/// <param name="tag">接口分组</param>
/// <param name="name">接口名称</param>
public SimApiDocAttribute(string tag, string name)
/// <param name="description">接口描述</param>
public SimApiDocAttribute(string tag, string name, string? description = null)
{
Tags = [tag];
Summary = name;
if (description != null)
{
Description = description;
}
// Consumes = new[] {"application/json"};
// Produces = new[] {"application/json"};
}
+118
View File
@@ -0,0 +1,118 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using SimApi.Exceptions;
using SimApi.Helpers;
using SimApi.ModelBinders;
namespace SimApi.Attributes;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SimApiSignAttribute : ActionFilterAttribute
{
public Type KeyProvider { get; set; } = typeof(SimApiSignProviderBase);
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.RequestServices.GetService(KeyProvider) is not SimApiSignProviderBase keyProvider)
{
throw new SimApiException(400, "未配置签名器");
}
string? appId = null;
if (!string.IsNullOrEmpty(keyProvider.AppIdName))
{
appId = context.HttpContext.Request.Query[keyProvider.AppIdName]
.FirstOrDefault() ?? context.HttpContext.Request.Headers[keyProvider.AppIdName]
.FirstOrDefault();
if (string.IsNullOrEmpty(appId))
{
throw new SimApiException(400, $"获取{keyProvider.AppIdName}失败");
}
}
// 4. 通过接口获取密钥(解耦的核心:不再直接依赖数据库)
var key = keyProvider.GetKey(appId);
if (string.IsNullOrEmpty(key))
{
throw new SimApiException(400, "获取签名KEY失败");
}
var timestamp = context.HttpContext.Request.Query[keyProvider.TimestampName]
.FirstOrDefault() ?? context.HttpContext.Request.Headers[keyProvider.TimestampName]
.FirstOrDefault();
if (string.IsNullOrEmpty(timestamp))
{
throw new SimApiException(400, $"{keyProvider.TimestampName}不能为空");
}
var nonce = context.HttpContext.Request.Query[keyProvider.NonceName]
.FirstOrDefault() ?? context.HttpContext.Request.Headers[keyProvider.NonceName]
.FirstOrDefault();
if (string.IsNullOrEmpty(nonce))
{
throw new SimApiException(400, $"{keyProvider.NonceName}不能为空");
}
if (!int.TryParse(timestamp, out var ts))
{
throw new SimApiException(400, $"{keyProvider.TimestampName}格式错误");
}
if (keyProvider.QueryExpires != 0)
{
if (ts > SimApiUtil.TimestampNow + 2)
{
throw new SimApiException(400, "请校准本地时间");
}
if (ts + keyProvider.QueryExpires < SimApiUtil.TimestampNow)
{
throw new SimApiException(400, "请求已过期");
}
if (keyProvider.DuplicateRequestProtection)
{
var cache = context.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
if (cache.GetString("SignQuery:" + nonce) == null)
{
cache.SetString("SignQuery:" + nonce, timestamp, new DistributedCacheEntryOptions()
{
SlidingExpiration = TimeSpan.FromSeconds(keyProvider.QueryExpires + 2)
});
}
else
{
throw new SimApiException(400, "重复请求");
}
}
}
var signStr = string.Empty;
foreach (var item in keyProvider.SignFields)
{
signStr += $"{item}=";
signStr += context.HttpContext.Request.Query[item]
.FirstOrDefault() ?? context.HttpContext.Request.Headers[item]
.FirstOrDefault();
signStr += "&";
}
if (!string.IsNullOrEmpty(keyProvider.AppIdName))
{
signStr += $"{keyProvider.AppIdName}={appId}&";
}
signStr += $"{keyProvider.TimestampName}={ts}&{keyProvider.NonceName}={nonce}&{key}";
var sign = context.HttpContext.Request.Query[keyProvider.SignName]
.FirstOrDefault() ?? context.HttpContext.Request.Headers[keyProvider.SignName]
.FirstOrDefault();
if (SimApiUtil.Md5(signStr) != sign)
{
throw new SimApiException(400, "签名错误");
}
}
}
+2 -10
View File
@@ -46,23 +46,15 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
}
/// <summary>
/// 动态内容分页
/// 分页内容返回
/// </summary>
/// <typeparam name="T"></typeparam>
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
public class PageResponse<T>
{
public T? List { get; set; }
public int Page { get; set; } = 1;
public int Count { get; set; } = 20;
public int Total { get; set; }
public SimApiBasePageResponse(T list, int page, int count, int total) : this()
{
List = list;
Page = page;
Count = count;
Total = total;
}
}
/// <summary>
+1 -1
View File
@@ -7,7 +7,7 @@ namespace SimApi.Communications;
/// </summary>
public class SimApiLoginItem
{
public string Id { get; set; } = null!;
public required string Id { get; set; }
public string[] Type { get; set; } = ["user"];
public Dictionary<string, string> Meta { get; set; } = [];
public object? Extra { get; set; }
+17
View File
@@ -4,13 +4,30 @@ public class SimApiJobOptions
{
/// <summary>
/// WebUi地址,设置为null表示不启用
/// 默认 /jobs
/// </summary>
public string? DashboardUrl { get; set; } = "/jobs";
/// <summary>
/// webui 用户
/// 默认 admin
/// </summary>
public string DashboardAuthUser { get; set; } = "admin";
/// <summary>
/// webui 密码
/// 默认 Admin@123!
/// </summary>
public string DashboardAuthPass { get; set; } = "Admin@123!";
/// <summary>
/// 设置为null 使用默认redis配置
/// </summary>
public string? RedisConfiguration { get; set; }
/// <summary>
/// 设置为null 使用默认redis配置
/// </summary>
public int? Database { get; set; } = null;
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
}
-46
View File
@@ -1,46 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using SimApi.Attributes;
namespace SimApi.Helpers
{
public class SimApiAuthOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// 检查接口或控制器是否标记了 [SimApiAuth] 特性
var requiresAuth =
// 方法上有 [SimApiAuth]
context.MethodInfo.GetCustomAttributes<SimApiAuthAttribute>(true).Any()
||
// 控制器上有 [SimApiAuth](继承到所有方法)
context.MethodInfo.DeclaringType?.GetCustomAttributes<SimApiAuthAttribute>(true).Any() == true;
if (requiresAuth)
{
// 添加授权要求:关联步骤 2 中定义的 "SimApiAuth" 安全方案
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "SimApiAuth" // 必须与 AddSecurityDefinition 的第一个参数一致
}
},
[] // 无需指定作用域(scope)时留空
}
}
};
}
// 未标记 [SimApiAuth] 的接口:不添加安全要求,Swagger 不显示锁图标
}
}
}
+89
View File
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using SimApi.Communications;
using SimApi.Exceptions;
namespace SimApi.Helpers;
public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
{
public string Server { get; init; } = string.Empty;
public string SignName { get; init; } = "sign";
public string TimestampName { get; init; } = "timestamp";
public string NonceName { get; init; } = "nonce";
public string? AppIdName { get; init; } = "appId";
public string[] SignFields { get; init; } = [];
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
{
url = Server + url;
var queryUrl = SignFields.Aggregate(string.Empty,
(current, signField) => current + $"{signField}={queries?[signField]}&");
if (!string.IsNullOrEmpty(AppIdName))
{
queryUrl += $"{AppIdName}={appId}&";
}
queryUrl += $"{TimestampName}={(int)SimApiUtil.TimestampNow}&{NonceName}={Guid.NewGuid()}";
var signStr = $"{queryUrl}&{appKey}";
var path = $"{url}?{queryUrl}&{SignName}={SimApiUtil.Md5(signStr)}";
if (queries != null)
{
path = queries.Where(q => !SignFields.Contains(q.Key))
.Aggregate(path, (current, q) => current + $"&{q.Key}={q.Value}");
}
return Query<T>(path, body);
}
public T? AesQuery<T>(string url, object body)
{
url = Server + url;
if (!string.IsNullOrEmpty(AppIdName))
{
url += $"?{AppIdName}={appId}";
}
var req = new SimApiOneFieldRequest<string>
{
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
};
return Query<T>(url, req);
}
public T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
{
var req = new SimApiOneFieldRequest<string>
{
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
};
return SignQuery<T>(url, req, queries);
}
private T? Query<T>(string url, object? req)
{
var http = new HttpClient();
if (debug)
{
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
}
var resp = http.PostAsJsonAsync(url, req).Result;
if (debug)
{
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
}
var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result;
if (res == null)
{
throw new SimApiException(500, "请求发生错误");
}
return res.Code != 200 ? throw new SimApiException(res.Code, res.Message) : res.Data;
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ public class SimApiJobWebAuth(string user, string pass) : IDashboardAuthorizatio
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
var authHeader = httpContext.Request.Headers["Authorization"].FirstOrDefault();
var authHeader = httpContext.Request.Headers.Authorization.FirstOrDefault();
if (authHeader != null && authHeader.StartsWith("Basic "))
{
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
+3
View File
@@ -24,6 +24,8 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
try
{
await next(context);
if (!context.Response.HasStarted)
{
switch (context.Response.StatusCode)
{
case 200:
@@ -36,6 +38,7 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
throw new SimApiException(context.Response.StatusCode);
}
}
}
catch (SimApiException ex)
{
response = string.IsNullOrEmpty(ex.Message)
+106
View File
@@ -0,0 +1,106 @@
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.ModelBinders;
public class AesBodyModelBinder : IModelBinder
{
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var request = bindingContext.HttpContext.Request;
request.EnableBuffering();
using var reader = new StreamReader(request.Body, leaveOpen: true);
var requestBody = await reader.ReadToEndAsync();
request.Body.Position = 0;
if (string.IsNullOrEmpty(requestBody))
{
bindingContext.ModelState.AddModelError("", "请求体不能为空");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
SimApiOneFieldRequest<string>? aesRequest;
try
{
aesRequest = JsonSerializer.Deserialize<SimApiOneFieldRequest<string>>(requestBody, SimApiUtil.JsonOption);
}
catch (JsonException ex)
{
bindingContext.ModelState.AddModelError("", $"请求体格式错误:{ex.Message}");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
if (aesRequest == null || string.IsNullOrEmpty(aesRequest.Data))
{
bindingContext.ModelState.AddModelError("", "请求体缺少密文Data字段");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
// 3. 根据配置获取appId(参考上一节代码)
var keyProvider =
bindingContext.HttpContext.RequestServices.GetService(Type.GetType(bindingContext.BinderModelName!)!) as
AesBodyProviderBase;
string? appId = null;
if (!string.IsNullOrEmpty(keyProvider!.AppIdName))
{
appId = bindingContext.HttpContext.Request.Query[keyProvider.AppIdName]
.FirstOrDefault() ?? bindingContext.HttpContext.Request.Headers[keyProvider.AppIdName]
.FirstOrDefault();
if (string.IsNullOrEmpty(appId))
{
bindingContext.ModelState.AddModelError("",
$"未找到{keyProvider.AppIdName}");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
}
// 4. 通过接口获取密钥(解耦的核心:不再直接依赖数据库)
var key = keyProvider.GetKey(appId);
if (string.IsNullOrEmpty(key))
{
bindingContext.ModelState.AddModelError("", "获取密钥失败(应用不存在或密钥未配置)");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
// 5. 解密和反序列化(保持原有逻辑)
try
{
var jsonStr = SimApiAesUtil.Decrypt(aesRequest.Data, key);
if (string.IsNullOrEmpty(jsonStr))
{
bindingContext.ModelState.AddModelError("", "解密失败");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
var targetType = bindingContext.ModelType;
var deserializedModel = JsonSerializer.Deserialize(jsonStr, targetType, SimApiUtil.JsonOption);
if (deserializedModel == null)
{
bindingContext.ModelState.AddModelError("", "反序列化失败");
bindingContext.Result = ModelBindingResult.Failed();
return;
}
bindingContext.Result = ModelBindingResult.Success(deserializedModel);
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError("", $"处理异常:{ex.Message}");
bindingContext.Result = ModelBindingResult.Failed();
}
}
}
+19
View File
@@ -0,0 +1,19 @@
using SimApi.Exceptions;
namespace SimApi.ModelBinders;
/// <summary>
/// 密钥提供器接口(抽象密钥获取逻辑)
/// </summary>
public abstract class AesBodyProviderBase
{
public virtual string? AppIdName { get; set; } = "appId";
/// <summary>
/// 根据appId获取对应的密钥
/// </summary>
/// <param name="appId">应用ID</param>
/// <returns>密钥(返回null表示获取失败)</returns>
public abstract string? GetKey(string? appId);
}
+45
View File
@@ -0,0 +1,45 @@
using SimApi.Exceptions;
namespace SimApi.ModelBinders;
public abstract class SimApiSignProviderBase
{
/// <summary>
/// appId字段的名称
/// </summary>
public virtual string? AppIdName { get; set; } = "appId";
/// <summary>
/// 时间戳的字段名
/// </summary>
public virtual string TimestampName { get; set; } = "timestamp";
/// <summary>
/// 随机字符串的字段名
/// </summary>
public virtual string NonceName { get; set; } = "nonce";
/// <summary>
/// 签名的字段名
/// </summary>
public virtual string SignName { get; set; } = "sign";
/// <summary>
/// 请求过期时间, 如果为0, 不校验timestamp
/// </summary>
public virtual int QueryExpires { get; set; } = 5;
/// <summary>
/// 如果开启,必须配置redis, 每次请求将会缓存nonce
/// </summary>
public virtual bool DuplicateRequestProtection { get; set; } = true;
public virtual string[] SignFields { get; set; } = [];
/// <summary>
/// 根据appId获取对应的密钥
/// </summary>
/// <param name="appId">应用ID</param>
/// <returns>密钥(返回null表示获取失败)</returns>
public abstract string? GetKey(string? appId);
}
+6 -6
View File
@@ -9,7 +9,7 @@
<Description>AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库</Description>
<PackageId>Simcu.SimApi</PackageId>
<Nullable>enable</Nullable>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
@@ -17,14 +17,14 @@
<Folder Include="Exceptions\"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.21" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0"/>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.10" />
<PackageReference Include="Minio" Version="6.0.5" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.1" />
<PackageReference Include="Minio" Version="7.0.0" />
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/>
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.6" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.6" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
+80 -7
View File
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
@@ -9,7 +10,7 @@ using Hangfire.Redis.StackExchange;
using SimApi.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi;
using SimApi.Middlewares;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
@@ -19,6 +20,7 @@ using SimApi.Attributes;
using SimApi.CoceSdk;
using SimApi.Configurations;
using SimApi.Logger;
using SimApi.SwaggerFilters;
namespace SimApi;
@@ -122,8 +124,80 @@ public static class SimApiExtensions
});
}
x.CustomSchemaIds(type => type.FullName?.Replace("+", "."));
x.OperationFilter<SimApiResponseSchemaFilter>();
x.CustomSchemaIds(type =>
{
// 递归解析类型名称(处理嵌套泛型/数组/可空 + 保证唯一性)
string GetSimpleTypeName(Type t, int depth = 0)
{
// 防止无限递归
if (depth > 5) return t.Name.Split('`')[0];
// 处理数组类型
if (t.IsArray)
{
var elementType = t.GetElementType();
return $"{GetSimpleTypeName(elementType, depth + 1)}[]";
}
// 处理可空类型
if (Nullable.GetUnderlyingType(t) != null)
{
var underlyingType = Nullable.GetUnderlyingType(t);
return GetSimpleTypeName(underlyingType, depth + 1);
}
// 处理泛型类型(递归解析嵌套泛型)
if (t.IsGenericType)
{
var genericBaseName = t.GetGenericTypeDefinition().Name.Split('`')[0];
var genericArgs = t.GetGenericArguments()
.Select(arg => GetSimpleTypeName(arg, depth + 1))
.Where(arg => !string.IsNullOrEmpty(arg))
.ToArray();
return $"{genericBaseName}<{string.Join(",", genericArgs)}>";
}
// 处理基础类型(小写)
if (t.IsPrimitive || t == typeof(string) || t == typeof(DateTime) || t == typeof(Guid))
{
return t.Name switch
{
"String" => "string",
"Int32" => "int",
"Int64" => "long",
"Boolean" => "boolean",
"DateTime" => "datetime",
"Guid" => "guid",
_ => t.Name.ToLower()
};
}
// 核心修复:生成唯一名称(处理嵌套类/同名不同类)
var typeName = t.Name;
// 步骤1:处理嵌套类(如 ApplicationDto+ApplicationEditRequest → ApplicationDto_ApplicationEditRequest
if (t.DeclaringType != null)
{
typeName = $"{GetSimpleTypeName(t.DeclaringType)}.{typeName}";
}
// 步骤2:(可选)处理同命名空间下的同名类(拼接命名空间前缀,避免全局重复)
// 如需更严格的唯一性,取消注释下面这行
// typeName = $"{t.Namespace?.Replace(".", "_")}_{typeName}";
return typeName;
}
// 根调用:解析当前类型
var uniqueSchemaId = GetSimpleTypeName(type);
// 可选:移除特殊字符(如 $、+),避免 Swagger 解析问题
return uniqueSchemaId.Replace("$", "").Replace("+", "_");
});
x.OperationFilter<SimApiResponseOperationFilter>();
x.OperationFilter<SimApiSignOperationFilter>();
x.OperationFilter<AesBodyOperationFilter>();
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
x.DocumentFilter<RemoveEmptyTagsFilter>();
if (simApiOptions.EnableSimApiAuth)
{
x.OperationFilter<SimApiAuthOperationFilter>();
@@ -153,11 +227,12 @@ public static class SimApiExtensions
switch (auth)
{
case "SimApiAuth":
x.AddSecurityDefinition("HeaderToken",
x.AddSecurityDefinition("SimApiAuth",
new OpenApiSecurityScheme
{
Name = "Token",
In = ParameterLocation.Header
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
break;
case "ClientCredentials":
@@ -236,7 +311,6 @@ public static class SimApiExtensions
if (simApiOptions.EnableSimApiResponseFilter)
{
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
.AddXmlSerializerFormatters()
.AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
@@ -389,7 +463,6 @@ public static class SimApiExtensions
x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name);
}
x.EnableValidator();
x.SupportedSubmitMethods(docOptions.SupportedMethod);
x.DisplayRequestDuration();
});
+796
View File
@@ -0,0 +1,796 @@
# SimApi 库使用说明书
## 1. 项目概述
SimApi 是一个基于 .NET 的基础辅助包,提供了一系列实用功能,帮助开发者快速构建和部署 API 服务。
### 主要功能特性:
- **统一的参数检测和错误处理**:自动验证请求参数并返回标准化的错误响应
- **基础认证服务**:基于 Header Token 的简单认证机制
- **S3 兼容的存储系统**:支持文件上传、下载和管理
- **任务调度系统**:基于 Hangfire 的后台任务管理
- **事件和 RPC 调用**:基于 RabbitMQ 的事件和 RPC 通信
- **自定义日志格式**:提供格式化的控制台日志
- **在线 API 文档**:基于 Swagger 的 API 文档生成
- **统一的响应格式**:标准化的 API 响应结构
- **CORS 配置**:支持跨域资源共享
- **版本管理**:提供应用版本和 SimApi 版本查询
## 2. 安装方法
### 通过 NuGet 安装:
```bash
Install-Package SimApi
```
### 项目集成
`Startup.cs``Program.cs` 中配置 SimApi
```csharp
// 在 ConfigureServices 方法中
services.AddSimApi(options =>
{
// 配置选项
});
// 在 Configure 方法中
app.UseSimApi();
```
## 3. 核心功能模块
### 3.1 基础控制器
所有控制器应继承自 `SimApiBaseController`,以获得统一的参数检测和错误处理功能。
```csharp
using SimApi.Controllers;
public class BaseController : SimApiBaseController
{
/// <summary>
/// 获取登录用户信息
/// </summary>
protected SimApiLoginItem LoginInfo => (SimApiLoginItem) HttpContext.Items["LoginInfo"];
}
```
### 3.2 认证服务
#### 配置认证服务:
```csharp
services.AddSimApi(options =>
{
options.EnableSimApiAuth = true;
});
```
#### 使用认证:
1. 在控制器或动作方法上添加 `[SimApiAuth]` 属性
2. 登录用户信息可通过 `LoginInfo` 属性获取
#### 认证相关接口:
- `POST /auth/check`:检测用户登录状态
- `POST /auth/logout`:用户退出登录
- `POST /user/info`:获取用户信息
### 3.3 存储服务
#### 配置存储服务:
```csharp
services.AddSimApi(options =>
{
options.EnableSimApiStorage = true;
options.SimApiStorageOptions = Configuration.GetSection("S3").Get<SimApiStorageOptions>();
});
```
#### 存储配置选项:
```json
{
"S3": {
"Endpoint": "http://localhost:9000",
"AccessKey": "minioadmin",
"SecretKey": "minioadmin",
"Bucket": "mybucket",
"ServeUrl": "http://localhost:9000/mybucket"
}
}
```
#### 使用存储服务:
```csharp
private readonly SimApiStorage _storage;
public MyController(SimApiStorage storage)
{
_storage = storage;
}
// 获取上传 URL
var uploadUrlResponse = _storage.GetUploadUrl("/path/to/file.txt");
// 获取下载 URL
var downloadUrl = _storage.GetDownloadUrl("/path/to/file.txt");
// 直接上传文件
using var stream = new MemoryStream();
_storage.UploadFile("/path/to/file.txt", stream, "text/plain");
// 获取完整访问 URL
var fullUrl = _storage.FullUrl("/path/to/file.txt");
```
### 3.4 任务调度系统
#### 配置任务调度:
```csharp
services.AddSimApi(options =>
{
options.EnableJob = true;
options.SimApiJobOptions = new SimApiJobOptions
{
DashboardUrl = "/jobs",
DashboardAuthUser = "admin",
DashboardAuthPass = "Admin@123!",
RedisConfiguration = "localhost:6379",
Servers = new[]
{
new SimApiJobServerConfig
{
Queues = new[] { "default" },
WorkerNum = 50
}
}
};
});
```
#### 使用任务调度:
```csharp
// 立即执行任务
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
// 延迟执行任务
BackgroundJob.Schedule(() => Console.WriteLine("Delayed job"), TimeSpan.FromMinutes(1));
// 重复执行任务
RecurringJob.AddOrUpdate("my-recurring-job", () => Console.WriteLine("Recurring job"), Cron.Hourly);
// 连续执行任务
var id = BackgroundJob.Enqueue(() => Console.WriteLine("First job"));
BackgroundJob.ContinueWith(id, () => Console.WriteLine("Second job"));
```
### 3.5 事件和 RPC 调用
#### 配置事件和 RPC
```csharp
services.AddSimApi(options =>
{
options.EnableSynapse = true;
options.SimApiSynapseOptions = new SimApiSynapseOptions
{
// 配置选项
};
});
```
#### 使用事件:
```csharp
// 发布事件
var synapse = serviceProvider.GetRequiredService<Synapse>();
synapse.PublishEvent("event-name", data);
// 订阅事件
[SynapseEvent("event-name")]
public void HandleEvent(dynamic data)
{
// 处理事件
}
```
#### 使用 RPC
```csharp
// 发布 RPC 调用
var result = await synapse.CallRpcAsync<string>("rpc-method", data);
// 实现 RPC 方法
[SynapseRpc("rpc-method")]
public string GetData(dynamic data)
{
return "Hello, RPC!";
}
```
### 3.6 在线 API 文档
#### 配置 API 文档:
```csharp
services.AddSimApi(options =>
{
options.EnableSimApiDoc = true;
options.ConfigureSimApiDoc(docOptions =>
{
docOptions.ApiGroups = new[]
{
new SimApiDocGroupOption
{
Id = "admin",
Name = "后台管理接口",
Description = "本接口调用需要Scopesac.api.admin"
},
new SimApiDocGroupOption
{
Id = "user-v1",
Name = "用户中心接口",
Description = "本接口调用需要Scopesac.api.user"
}
};
docOptions.ApiAuth = new SimApiAuthOption
{
Type = new[] { "ClientCredentials", "Implicit", "AuthorizationCode" },
Scopes = new Dictionary<string, string>
{
{ "sac.api.user", "用户信息接口权限" },
{ "sac.api.admin", "后台管理API" }
},
AuthorizationUrl = "/connect/authorize",
TokenUrl = "/connect/token"
};
});
});
```
#### 访问 API 文档:
启动应用后,访问 `/swagger` 查看 API 文档。
### 3.7 统一响应格式
#### 配置响应过滤器:
```csharp
services.AddSimApi(options =>
{
options.EnableSimApiResponseFilter = true;
});
```
#### 响应过滤器实现:
SimApi 提供了 `SimApiResponseFilter` 结果过滤器,用于自动封装 API 响应为统一格式:
- 自动将 `null` 结果封装为 `{"Code": 200, "Message": "成功"}`
- 自动将普通对象结果封装为 `{"Code": 200, "Message": "成功", "Data": 对象}`
- 自动将 `EmptyResult` 封装为 `{"Code": 200, "Message": "成功"}`
- 保持 `SimApiBaseResponse` 类型的结果不变
#### 异常中间件:
SimApi 还提供了 `SimApiExceptionMiddleware` 异常中间件,用于统一处理异常:
- 捕获所有未处理的异常
- 将异常转换为标准化的错误响应格式
- 处理 HTTP 状态码,如 404 等
- 记录错误日志
#### 使用响应格式:
```csharp
// 无数据响应
return new SimApiBaseResponse();
// 带数据响应
return new SimApiBaseResponse<User>(user);
// 直接返回对象,会自动被封装
return user;
// 错误响应
Error(400, "参数错误");
// 条件错误检查
ErrorWhenNull(user, 404, "用户不存在");
ErrorWhen(user.Age < 18, 403, "未满18岁,无权访问");
```
#### 原始响应标记:
如果需要返回原始响应格式,不使用统一封装,可以在控制器或动作方法上添加 `[OriginResponse]` 属性:
```csharp
[HttpGet]
[OriginResponse] // 返回原始响应格式
public string GetRawData()
{
return "原始字符串响应";
}
```
## 4. API 参考
### 4.1 核心类
#### SimApiUtil
**命名空间**`SimApi.Helpers`
**描述**:提供一系列静态工具方法和属性,用于常见操作。
**主要属性**
- `CstNow`:获取当前 CST(中国标准时间)
- `JsonOption`JSON 序列化常规选项
- `SimApiVersion`:获取 SimApi 库版本
- `AppVersion`:获取应用版本
- `TimestampNow`:获取当前秒级时间戳
**主要方法**
- `CheckCell(string cell)`:检测手机号是否正确
- `Md5(string source, string mode = "x2")`MD5 加密字符串
- `Sha1(string source, string mode = "x2")`SHA1 加密字符串
- `XmlDeserialize<T>(string source)`:将 XML 字符串序列化为对象
- `Json(object? obj)`:将对象序列化为 JSON 字符串
- `Paginate<T>(this IQueryable<T> query, int page, int count)`:分页扩展方法
**使用示例**
```csharp
// 获取当前时间
var now = SimApiUtil.CstNow;
// JSON 序列化
var json = SimApiUtil.Json(new { Name = "Test", Age = 18 });
// MD5 加密
var md5 = SimApiUtil.Md5("password");
// 分页
var query = dbContext.Users.AsQueryable();
var paginatedQuery = query.Paginate(1, 10);
// 获取版本信息
var simApiVersion = SimApiUtil.SimApiVersion;
var appVersion = SimApiUtil.AppVersion;
```
#### SimApiExtensions
**命名空间**`SimApi`
**描述**:提供一系列扩展方法,用于配置和使用 SimApi。
**主要方法**
- `AddSimApi(this IServiceCollection builder, Action<SimApiOptions>? options = null)`:向服务集合添加 SimApi 服务和配置
- `UseSimApi(this IHost builder)`:在主机上使用 SimApi
- `UseSimApi(this WebApplication builder)`:在 Web 应用上使用 SimApi,配置中间件和路由
**使用示例**
```csharp
// 在 ConfigureServices 方法中
services.AddSimApi(options =>
{
// 配置选项
options.EnableSimApiDoc = true;
options.EnableSimApiAuth = true;
// 其他配置...
});
// 在 Configure 方法中
app.UseSimApi();
```
#### SimApiBaseController
**继承自**`Controller`
**主要方法**
- `Error(int code = 500, string message = "")`:抛出错误异常
- `ErrorWhen(bool condition, int code = 400, string message = "")`:当条件为真时抛出错误
- `ErrorWhenNull(object? condition, int code = 404, string message = "请求的资源不存在")`:当对象为 null 时抛出错误
- `UploadFile()`:上传文件
**属性**
- `LoginInfo`:获取当前登录用户信息
#### SimApiAuth
**主要方法**
- `Login(SimApiLoginItem loginItem, string? token = null)`:登录用户并返回 token
- `Update(SimApiLoginItem loginItem, string token)`:更新用户登录信息
- `GetLogin(string token)`:根据 token 获取登录信息
- `Logout(string uuid)`:退出登录
#### SimApiStorage
**主要方法**
- `GetUploadUrl(string path, int expire = 7200)`:获取文件上传 URL
- `GetDownloadUrl(string path, int expire = 600)`:获取文件下载 URL
- `UploadFile(string path, Stream stream, string contentType = "image/png")`:上传文件
- `FullUrl(string? path)`:获取完整的文件访问 URL
- `GetUrl(string? path)`:获取文件访问 URL
- `GetPath(string? url)`:从 URL 中获取相对路径
#### SimApiBaseResponse
**构造函数**
- `SimApiBaseResponse(int code = 200, string message = "成功")`:创建响应对象
**属性**
- `Code`:响应代码
- `Message`:响应消息
#### SimApiBaseResponse<T>
**继承自**`SimApiBaseResponse`
**构造函数**
- `SimApiBaseResponse(T data)`:创建带数据的响应对象
**属性**
- `Data`:响应数据
### 4.2 配置类
#### SimApiOptions
**主要属性**
- `RedisConfiguration`Redis 配置字符串
- `EnableJob`:是否启用任务调度系统
- `EnableSimApiAuth`:是否启用认证服务
- `EnableCoceSdk`:是否启用 CoceSdk
- `EnableSimApiStorage`:是否启用存储服务
- `EnableSimApiDoc`:是否启用 API 文档
- `EnableSynapse`:是否启用事件和 RPC
- `EnableCors`:是否启用 CORS
- `EnableSimApiException`:是否启用异常拦截
- `EnableSimApiResponseFilter`:是否启用响应过滤器
- `EnableForwardHeaders`:是否启用 Header 转发
- `EnableLowerUrl`:是否启用小写 URL
- `EnableVersionUrl`:是否启用版本查询
- `EnableLogger`:是否启用自定义日志
**配置方法**
- `ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)`:配置 API 文档
- `ConfigureSimApiStorage(Action<SimApiStorageOptions>? options = null)`:配置存储服务
- `ConfigureSimApiJob(Action<SimApiJobOptions>? options = null)`:配置任务调度
- `ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)`:配置事件和 RPC
- `ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)`:配置 CoceSdk
## 5. 配置选项
### 5.1 存储配置 (SimApiStorageOptions)
```csharp
public class SimApiStorageOptions
{
public string? Endpoint { get; set; } // S3 服务端点
public string? AccessKey { get; set; } // 访问密钥
public string? SecretKey { get; set; } // 密钥
public string? Bucket { get; set; } // 存储桶名称
public string? ServeUrl { get; set; } // 访问 URL
}
```
### 5.2 任务调度配置 (SimApiJobOptions)
```csharp
public class SimApiJobOptions
{
public string? DashboardUrl { get; set; } = "/jobs"; // Web UI 地址
public string DashboardAuthUser { get; set; } = "admin"; // Web UI 用户名
public string DashboardAuthPass { get; set; } = "Admin@123!"; // Web UI 密码
public string? RedisConfiguration { get; set; } // Redis 配置
public int? Database { get; set; } = null; // Redis 数据库
public SimApiJobServerConfig[] Servers { get; set; } = [new()]; // 服务器配置
}
public class SimApiJobServerConfig
{
public string[] Queues { get; set; } = ["default"]; // 队列名称
public int WorkerNum { get; set; } = 50; // 工作线程数
}
```
### 5.3 API 文档配置 (SimApiDocOptions)
```csharp
public class SimApiDocOptions
{
public string DocumentTitle { get; set; } = "API 文档"; // 文档标题
public SimApiDocGroupOption[] ApiGroups { get; set; } = []; // API 分组
public SimApiAuthOption ApiAuth { get; set; } = new(); // 认证配置
public string[] SupportedMethod { get; set; } = ["GET", "POST", "PUT", "DELETE"]; // 支持的 HTTP 方法
}
public class SimApiDocGroupOption
{
public string Id { get; set; } = "api"; // 分组 ID
public string Name { get; set; } = "API"; // 分组名称
public string Description { get; set; } = ""; // 分组描述
}
public class SimApiAuthOption
{
public string[] Type { get; set; } = []; // 认证类型
public Dictionary<string, string> Scopes { get; set; } = []; // 权限范围
public string AuthorizationUrl { get; set; } = "/connect/authorize"; // 授权 URL
public string TokenUrl { get; set; } = "/connect/token"; // Token URL
public string Description { get; set; } = ""; // 认证描述
}
```
## 6. 使用示例
### 6.1 完整配置示例
```csharp
services.AddSimApi(options =>
{
// 配置 Redis
options.RedisConfiguration = "localhost:6379";
// 配置 API 文档
options.EnableSimApiDoc = true;
options.ConfigureSimApiDoc(docOptions =>
{
docOptions.ApiGroups = new[]
{
new SimApiDocGroupOption
{
Id = "admin",
Name = "后台管理接口",
Description = "本接口调用需要Scopesac.api.admin"
},
new SimApiDocGroupOption
{
Id = "user-v1",
Name = "用户中心接口",
Description = "本接口调用需要Scopesac.api.user"
}
};
docOptions.ApiAuth = new SimApiAuthOption
{
Type = new[] { "ClientCredentials", "Implicit", "AuthorizationCode" },
Scopes = new Dictionary<string, string>
{
{ "sac.api.user", "用户信息接口权限" },
{ "sac.api.admin", "后台管理API" }
},
AuthorizationUrl = "/connect/authorize",
TokenUrl = "/connect/token"
};
});
// 配置存储服务
options.EnableSimApiStorage = true;
options.SimApiStorageOptions = Configuration.GetSection("S3").Get<SimApiStorageOptions>();
// 配置任务调度
options.EnableJob = true;
options.ConfigureSimApiJob(jobOptions =>
{
jobOptions.DashboardUrl = "/jobs";
jobOptions.DashboardAuthUser = "admin";
jobOptions.DashboardAuthPass = "Admin@123!";
});
// 配置事件和 RPC
options.EnableSynapse = true;
// 其他配置
options.EnableCors = true;
options.EnableSimApiException = true;
options.EnableSimApiResponseFilter = true;
options.EnableVersionUrl = true;
options.EnableLogger = true;
});
// 使用 SimApi
app.UseSimApi();
```
### 6.2 控制器示例
```csharp
using Microsoft.AspNetCore.Mvc;
using SimApi.Controllers;
using SimApi.Helpers;
[ApiController]
[Route("[controller]")]
public class UserController : BaseController
{
private readonly SimApiStorage _storage;
public UserController(SimApiStorage storage)
{
_storage = storage;
}
[HttpGet("{id}")]
public SimApiBaseResponse<User> GetUser(int id)
{
var user = GetUserFromDatabase(id);
ErrorWhenNull(user, 404, "用户不存在");
return new SimApiBaseResponse<User>(user);
}
[HttpPost]
[SimApiAuth] // 需要认证
public SimApiBaseResponse<User> CreateUser(UserCreateDto dto)
{
ErrorWhen(string.IsNullOrEmpty(dto.Name), 400, "用户名不能为空");
ErrorWhen(dto.Age < 18, 400, "年龄必须大于18岁");
var user = CreateUserInDatabase(dto);
return new SimApiBaseResponse<User>(user);
}
[HttpPost("upload-avatar")]
[SimApiAuth]
public async Task<SimApiBaseResponse<string>> UploadAvatar(IFormFile file)
{
using var stream = file.OpenReadStream();
var path = $"/avatars/{LoginInfo.Id}/{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
_storage.UploadFile(path, stream, file.ContentType);
var url = _storage.GetUrl(path);
return new SimApiBaseResponse<string>(url);
}
}
```
### 6.3 任务调度示例
```csharp
public class UserService
{
public void SendWelcomeEmail(string email)
{
// 发送欢迎邮件
Console.WriteLine($"Sending welcome email to {email}");
}
public void CleanupInactiveUsers()
{
// 清理不活跃用户
Console.WriteLine("Cleaning up inactive users");
}
public void GenerateMonthlyReport()
{
// 生成月度报告
Console.WriteLine("Generating monthly report");
}
}
// 配置任务
public void ConfigureJobs(IServiceProvider serviceProvider)
{
// 立即发送欢迎邮件
BackgroundJob.Enqueue<UserService>(x => x.SendWelcomeEmail("user@example.com"));
// 每天凌晨清理不活跃用户
RecurringJob.AddOrUpdate<UserService>("cleanup-inactive-users", x => x.CleanupInactiveUsers(), Cron.Daily);
// 每月1日生成月度报告
RecurringJob.AddOrUpdate<UserService>("generate-monthly-report", x => x.GenerateMonthlyReport(), "0 0 1 * *");
}
```
## 7. 最佳实践
### 7.1 控制器设计
- 所有控制器应继承自 `SimApiBaseController` 或其派生类
- 使用 `Error``ErrorWhen` 系列方法进行错误处理
- 对需要认证的接口使用 `[SimApiAuth]` 属性
- 合理使用 API 分组,便于文档管理
### 7.2 存储管理
- 为不同类型的文件使用不同的存储路径结构
- 合理设置文件 URL 的过期时间
- 对上传的文件进行验证和处理
- 考虑使用 CDN 加速文件访问
### 7.3 任务调度
- 合理设置任务的队列和优先级
- 对长时间运行的任务进行分解
- 监控任务的执行状态和结果
- 合理设置任务的重试策略
### 7.4 事件和 RPC
- 为事件和 RPC 方法使用清晰的命名规范
- 合理设计事件和 RPC 的数据结构
- 考虑事件处理的幂等性
- 监控事件和 RPC 的执行情况
### 7.5 配置管理
- 使用配置文件或环境变量管理配置
- 对敏感配置进行加密处理
- 不同环境使用不同的配置
- 定期审查和更新配置
### 7.6 性能优化
- 合理使用缓存减少数据库访问
- 对高频访问的接口进行优化
- 考虑使用异步方法提高并发性能
- 监控系统性能并进行调优
## 8. 故障排查
### 8.1 常见问题
#### 认证失败
- 检查 Token 是否正确
- 检查 Redis 是否正常运行
- 检查认证中间件是否正确配置
#### 存储服务错误
- 检查 S3 服务是否正常运行
- 检查存储配置是否正确
- 检查网络连接是否正常
#### 任务调度错误
- 检查 Hangfire 仪表盘是否可访问
- 检查 Redis 是否正常运行
- 检查任务代码是否有异常
#### API 文档生成错误
- 检查 Swagger 配置是否正确
- 检查控制器和方法的注释是否完整
- 检查模型类是否有循环引用
### 8.2 日志和监控
- 启用 `EnableLogger` 配置查看详细日志
- 使用应用性能监控工具监控系统状态
- 定期检查系统日志和错误报告
- 设置关键指标的告警机制
## 9. 版本管理
- 访问 `/versions` 查看应用版本和 SimApi 版本
- 定期更新 SimApi 到最新版本
- 注意版本升级时的兼容性问题
- 遵循语义化版本规范管理应用版本
## 10. 总结
SimApi 是一个功能丰富的 .NET 基础辅助包,提供了一系列实用功能,帮助开发者快速构建和部署 API 服务。通过合理配置和使用 SimApi,可以显著提高开发效率,减少重复代码,提高系统的可维护性和可靠性。
本说明书提供了 SimApi 的详细使用方法和最佳实践,希望能帮助开发者更好地使用这个库。如果有任何问题或建议,欢迎反馈和贡献。
+53
View File
@@ -0,0 +1,53 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi;
using SimApi.Attributes;
namespace SimApi.SwaggerFilters;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
/// <summary>
/// 自定义 Swagger 过滤器:将标注 [AesBody] 的参数显示在 Request Body 中
/// </summary>
public class AesBodyOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
foreach (var parameter in context.ApiDescription.ParameterDescriptions)
{
var hasAesBodyAttr = parameter.ParameterInfo()
.GetCustomAttribute<AesBodyAttribute>() != null;
if (!hasAesBodyAttr) continue;
// 1. 移除默认的 Query 参数描述(如果存在)
var queryParam = operation.Parameters
.FirstOrDefault(p => p.Name == parameter.Name);
if (queryParam != null)
{
operation.Parameters.Remove(queryParam);
}
// 2. 添加 Body 参数描述
// 获取参数类型的 SchemaSwagger 模型定义)
var schema = context.SchemaGenerator.GenerateSchema(
parameter.Type,
context.SchemaRepository);
// 将参数添加到 Request Body
operation.RequestBody = new OpenApiRequestBody
{
Content = new Dictionary<string, OpenApiMediaType>
{
{
"application/json", // 假设使用 JSON 格式
new OpenApiMediaType { Schema = schema }
}
},
Description = "内容为加密前内容,需要转换为JSON后使用AES加密后提交,提交格式为 {\"data\":\"AES密文\"}",
Required = true // 标记为必填
};
}
}
}
@@ -0,0 +1,70 @@
using System;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections;
using System.Collections.Generic;
using System.Text.Json.Nodes;
namespace SimApi.SwaggerFilters;
public class GlobalDynamicObjectSchemaFilter : ISchemaFilter
{
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
{
if (!IsDynamicObjectType(context.Type)) return;
var oaSchema = schema as OpenApiSchema;
oaSchema.AdditionalPropertiesAllowed = true;
oaSchema.AdditionalProperties = new OpenApiSchema
{
Type = JsonSchemaType.Object, // 表示 value 可以是任意类型(兼容所有类型)
};
// 2. 覆盖默认示例,使用包含多种类型的示例
oaSchema.Example = CreateMultiTypeExample();
}
// 判断是否为需要处理的“动态对象”类型
private bool IsDynamicObjectType(Type? type)
{
if (type == null) return false;
if (typeof(IDictionary).IsAssignableFrom(type) ||
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
{
return true;
}
if (type == typeof(object))
{
return true;
}
return type.Name.Contains("AnonymousType") && type.Namespace == null;
}
// 创建包含多种类型的示例(覆盖默认的 string 示例)
private JsonNode CreateMultiTypeExample()
{
return new JsonObject
{
// 字符串类型:JsonValue.Create 包装字符串
["stringProp"] = JsonValue.Create("example string"),
// 数字类型:支持 int/long/double 等,JsonValue 自动适配
["numberProp"] = JsonValue.Create(123),
// 布尔类型
["boolProp"] = JsonValue.Create(true),
// 嵌套对象:JsonObject 对应 OpenApiObject
["objectProp"] = new JsonObject
{
["nestedKey"] = JsonValue.Create("nested value")
},
// 数组类型:JsonArray 对应 OpenApiArray
["arrayProp"] = new JsonArray
{
JsonValue.Create(1), // 数组内数字
JsonValue.Create("two") // 数组内字符串
},
// 可选:添加 null 值示例(若需要)
["nullProp"] = null
};
}
}
+25
View File
@@ -0,0 +1,25 @@
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
namespace SimApi.SwaggerFilters;
public class RemoveEmptyTagsFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
// 步骤1:收集所有有接口的 Tag 名称
var tagsWithOperations = swaggerDoc.Paths.Values
.SelectMany(path => path.Operations.Values)
.SelectMany(op => op.Tags.Select(t => t.Name))
.Distinct()
.ToList();
// 步骤2:移除无接口的空 Tag
var emptyTags = swaggerDoc.Tags.Where(t => !tagsWithOperations.Contains(t.Name)).ToList();
foreach (var tag in emptyTags)
{
swaggerDoc.Tags.Remove(tag);
}
}
}
@@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using SimApi.Attributes;
namespace SimApi.SwaggerFilters
{
public class SimApiAuthOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// 检查接口或控制器是否标记了 [SimApiAuth] 特性
var requiresAuth =
// 方法上有 [SimApiAuth]
context.MethodInfo.GetCustomAttributes<SimApiAuthAttribute>(true).Any()
||
// 控制器上有 [SimApiAuth](继承到所有方法)
context.MethodInfo.DeclaringType?.GetCustomAttributes<SimApiAuthAttribute>(true).Any() == true;
if (!requiresAuth) return;
operation.Security ??= new List<OpenApiSecurityRequirement>();
operation.Security.Add(new OpenApiSecurityRequirement()
{
{ new OpenApiSecuritySchemeReference("SimApiAuth", context.Document), [] }
});
}
}
}
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using System.Threading.Tasks;
@@ -9,9 +9,9 @@ using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
namespace SimApi.Helpers;
namespace SimApi.SwaggerFilters;
public class SimApiResponseSchemaFilter : IOperationFilter
public class SimApiResponseOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
+101
View File
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi;
using SimApi.Attributes;
using SimApi.ModelBinders;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace SimApi.SwaggerFilters;
public class SimApiSignOperationFilter(IServiceProvider serviceProvider) : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// 1. 检查当前方法或类是否标注了 SimApiSignAttribute 及其子类
var signAttribute = context.MethodInfo.GetCustomAttribute<SimApiSignAttribute>(inherit: true)
?? context.MethodInfo.DeclaringType?.GetCustomAttribute<SimApiSignAttribute>(inherit: true);
if (signAttribute == null)
{
return;
}
var keyProviderType = signAttribute.KeyProvider;
if (!typeof(SimApiSignProviderBase).IsAssignableFrom(keyProviderType))
{
throw new InvalidOperationException($"KeyProvider 必须继承自 {nameof(SimApiSignProviderBase)}");
}
SimApiSignProviderBase? keyProvider;
try
{
keyProvider =
serviceProvider.CreateScope().ServiceProvider.GetService(keyProviderType) as SimApiSignProviderBase;
}
catch (Exception ex)
{
throw new InvalidOperationException($"无法从 DI 容器获取 {keyProviderType.Name} 实例:{ex.Message}");
}
if (keyProvider == null)
{
throw new InvalidOperationException($"{keyProviderType.Name} 未在 DI 容器中注册");
}
var signStr = keyProvider.SignFields.Aggregate(string.Empty, (current, field) => current + $"{field}=xxx&");
if (!string.IsNullOrEmpty(keyProvider.AppIdName))
{
signStr += $"{keyProvider.AppIdName}=xxx&";
}
signStr += $"{keyProvider.TimestampName}=xxx&{keyProvider.NonceName}=xxx&签名密钥";
var signParameters = new List<(string Name, string Description, bool Required)>
{
(keyProvider.TimestampName, "时间戳(秒级)", true),
(keyProvider.NonceName, "随机字符串", true),
(keyProvider.SignName, $"MD5签名结果,签名MD5字符串: {signStr}", true)
};
if (keyProvider.AppIdName != null)
{
signParameters.Add((keyProvider.AppIdName, "应用标识", true));
}
signParameters.AddRange(keyProvider.SignFields.Where(x => x != keyProvider.AppIdName)
.Select(f => (f, string.Empty, true)));
operation.Parameters ??= new List<IOpenApiParameter>();
foreach (var (name, description, required) in signParameters)
{
if (operation.Parameters?.Any(p => p.Name == name) == true)
{
var tmp = operation.Parameters?.FirstOrDefault(p => p.Name == name);
if (tmp is OpenApiParameter concreteParam)
{
// 重新赋值只读属性(通过实例化新对象覆盖,或直接修改具体类的可写属性)
concreteParam.Required = required; // OpenApiParameter 的 Required 有 setter
concreteParam.Description = description;
}
continue;
}
operation.Parameters ??= new List<IOpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter
{
Name = name,
In = ParameterLocation.Query, // 指定为 Query 参数
Description = description,
Required = required,
Schema = new OpenApiSchema
{
Type = JsonSchemaType.String // 签名相关参数通常为字符串类型
}
});
}
}
}