Compare commits

...
66 Commits
Author SHA1 Message Date
xrain a859986a93 fix csproj 2026-04-24 09:29:02 +08:00
xrain e1c6694e18 fix ex aggr 2026-04-14 13:38:19 +08:00
xrain 566b1d190b add AiContext 2026-04-07 10:55:46 +08:00
xrain eb8c9732bd 修改了说明书 2026-04-07 10:44:34 +08:00
xrain c8b78ce86d add tags for doc 2026-03-26 00:52:52 +08:00
xrain b2ec94e957 fix ci 2026-03-26 00:41:55 +08:00
xrain a8439c174c SimApiDoc增加了描述 2026-03-26 00:32:20 +08:00
xrain 81e166ad45 修正了swgger生成的类型名,SimApiAuth 如果不加参数,则默认接受所有登录了的用户请求. 2025-12-23 08:18:11 +08:00
xrain d50d32f032 优化了文档中的类型名称,修复了认证接口不显示需要认证 2025-12-23 07:20:34 +08:00
xrain 8ad43526fc 修正了文档认证不显示的问题 2025-12-23 06:00:33 +08:00
xrain e2d30c031d 隐藏了文档中空Tag, 禁用了文档远程校验 2025-12-19 13:37:58 +08:00
xrain 9dc4ef7bce http client 增加了DebugLog 2025-12-18 16:17:18 +08:00
xrain d5eb7fe081 分页修改了,不在使用单独的分页返回,httpclient 不需要simaporesponse的包装,报错直接抛出异常 2025-12-18 14:06:11 +08:00
xrain b04a7c86d7 signQuery body defaultNull 2025-12-18 13:05:05 +08:00
xrain 8759b593db SimApiHttpClientAddServer 2025-12-18 11:28:47 +08:00
xrainandGitHub 5a46a026a7 Update nuget-publish.yml
fix ci
2025-12-18 09:13:19 +08:00
xrain 90124b6e67 update v10 2025-12-18 09:08:35 +08:00
xrain 2499912204 update package 2025-11-09 19:41:37 +08:00
xrain dd38f315d5 remove xml , support object to any in openapi 2025-11-09 19:36:21 +08:00
xrain c448381f23 fix middleware bug 2025-11-03 21:41:35 +08:00
xrain 8d5b667c88 fix 2025-11-02 22:18:25 +08:00
xrain 65451d7b80 fix swagger, add simapihttpclient 2025-11-02 22:14:34 +08:00
xrain c7373da691 add aesbody for get aes cryptbody 2025-11-02 18:58:01 +08:00
xrain 9a8d14142a version move to common 2025-11-01 21:38:55 +08:00
xrain cb89a1a003 doc only appear in current group 2025-11-01 18:40:51 +08:00
xrain 462bce50cc fix pack bug 2025-11-01 15:50:11 +08:00
xrain fed44c6b49 fix api ui, add versions 2025-11-01 15:42:12 +08:00
xrain c73aa1d2a8 fix api ui, add versions 2025-11-01 15:40:55 +08:00
xrain af6bc86a0c ErrorWhen Code Antis 2025-10-26 01:08:07 +08:00
xrain fc7714198f add loginitem update 2025-10-25 17:12:39 +08:00
xrain d2b5f14e78 fix some 2025-10-25 17:03:43 +08:00
xrain 116cbcdc7f update to 9 2025-10-14 02:55:29 +08:00
xrain 4e1b7d4845 update to 9 2025-10-14 02:20:37 +08:00
xrain 71acb35df9 cancle json refrence 2025-08-13 17:28:24 +08:00
xrain 67cc7346dc use concurrentDic 2025-05-17 21:17:43 +08:00
xrain 8627ae61fa use lock 2025-05-17 21:11:27 +08:00
xrain 02523028db add task.run 2025-05-17 20:40:48 +08:00
xrain 7d39ab5e0b add task.run 2025-05-17 20:38:39 +08:00
xrain 87fda473d3 udpate 2025-05-14 06:26:10 +08:00
xrain 4ae72d2e6b add CoceLoginProcessor 2025-01-17 01:30:13 +08:00
xrain afea9c82bd add hangfire 2025-01-16 22:05:59 +08:00
xrain e53048a980 update option 2024-12-23 22:11:00 +08:00
xrain bbc2806995 add origin response attribute 2024-12-23 20:34:38 +08:00
xrain 404a638d5e add filter 2024-12-23 20:26:21 +08:00
xrain e27d5e1c77 fix data 2024-09-08 14:42:51 +08:00
xrain 6af68da3eb timeout rpc supported 2024-09-05 15:06:44 +08:00
xrain 7dc2ac6a86 add headers 2024-09-05 12:59:57 +08:00
xrain 8f6b853b6c fix rpc ex , add RpcError Method 2024-08-25 00:11:00 +08:00
xrain e876486c00 fix rpc ex , add RpcError Method 2024-08-25 00:10:00 +08:00
xrain e71226be4a fix rpc ex , add RpcError Method 2024-08-25 00:08:06 +08:00
xrain bd674dcc31 add cocesdk 2024-08-19 03:39:35 +08:00
xrain 141846d79d 1. RpcServer can return not found , 2. Event server process all parllels 2024-08-05 19:55:14 +08:00
xrain a4bae0226e fix bug 2024-08-03 19:37:40 +08:00
xrain 15f74b6570 fix warning 2024-08-03 19:21:23 +08:00
xrain ac4619a789 fix warning 2024-08-03 19:19:42 +08:00
xrain 4d0f801f21 now mqtt reconnect will resub topic 2024-08-03 18:35:01 +08:00
xrain 683cf9176a add event loadbalancing 2024-07-27 01:33:17 +08:00
xrain 1ee8d941e9 fix eventserver bug 2024-07-26 19:18:59 +08:00
xrain 1d474f596a config fix 2024-07-26 08:56:01 +08:00
xrain 929ddaced3 add config store 2024-07-26 08:11:21 +08:00
xrain 82f7e0fc00 use Task insteadof while improve performance 2024-07-26 05:20:27 +08:00
xrain f4bc6dc080 fix synapse use mqtt 2024-07-26 05:03:28 +08:00
xrain 56b0490d1e fix log color 2024-07-24 21:50:46 +08:00
xrain 45e19c3561 fix log color 2024-07-24 21:43:31 +08:00
xrain 04b2be1bb7 fix bug 2024-07-21 13:50:12 +08:00
xrain f78c3a0e0d fix fullurl 不抛出异常了 2024-07-10 06:35:19 +08:00
57 changed files with 5130 additions and 706 deletions
+12 -7
View File
@@ -9,16 +9,21 @@ jobs:
publish:
name: Publish Project to Nuget
runs-on: ubuntu-latest
permissions:
id-token: write
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: "8.0.200"
dotnet-version: "10.x.x"
- name: NuGet login (OIDC → temp API key)
uses: NuGet/login@v1
id: login
with:
user: ${{ secrets.NUGET_USER }}
- name: Publish
run: |
version=`git describe --tags`
dotnet build --configuration release -p:PackageVersion=$version
dotnet nuget push bin/release/Simcu.SimApi.$version.nupkg -k ${NUGET_APIKEY} -s https://www.nuget.org/api/v2/package
env:
NUGET_APIKEY: ${{ secrets.NUGET_APIKEY }}
dotnet build --configuration release -p:Version=$version
dotnet nuget push bin/release/Simcu.SimApi.$version.nupkg -k ${{steps.login.outputs.NUGET_API_KEY}} -s https://api.nuget.org/v3/index.json
+574
View File
@@ -0,0 +1,574 @@
# SimApi AI Context
> NuGet: `Simcu.SimApi` | .NET 8/9/10 | ASP.NET Core API 基础库
---
## SETUP
```csharp
// Program.cs
builder.Services.AddSimApi(options => { ... });
var app = builder.Build();
app.UseSimApi();
app.Run();
```
---
## CORE GOTCHAS(必读,AI 容易犯的错)
| ❌ 错误 | ✅ 正确 |
|---------|---------|
| `SupportedMethod` 写多个方法 | 默认仅 `POST`,按需显式添加 |
| `WorkerNum = 50` | 默认是 `5` |
| 存储路径不加斜杠 `/avatars/file.jpg` | 路径必须以 `/` 开头 |
| `s.Endpoint = "http://minio:9000/"` | `ServeUrl`/`Endpoint` 不能以 `/` 结尾 |
| `synapse.PublishEvent(...)` | 方法名是 `synapse.Event(...)` |
| `synapse.CallRpcAsync(...)` | 方法名是 `synapse.Rpc<T>(...)` |
| HTTP 状态码 4xx/5xx 表示错误 | **所有错误均 HTTP 200**,错误在 JSON `code` 字段 |
| MQTT 用 RabbitMQ | **用 MQTTnet v5,通过 WebSocket 连接** |
| `SimApiStorageOptions = Configuration.GetSection(...)` | 用 `options.ConfigureSimApiStorage(s => {...})` |
---
## SimApiOptionsAddSimApi 配置)
```csharp
options.RedisConfiguration = "localhost:6379"; // 多模块共用
options.EnableSimApiAuth = false; // Token 认证
options.EnableSimApiDoc = false; // Swagger
options.EnableSimApiStorage = false; // S3 存储
options.EnableJob = false; // Hangfire
options.EnableSynapse = false; // MQTT
options.EnableCoceSdk = false; // Coce 身份
// 以下默认 true,通常不需要改:
options.EnableCors = true;
options.EnableSimApiException = true;
options.EnableSimApiResponseFilter = true;
options.EnableForwardHeaders = true;
options.EnableLowerUrl = true;
options.EnableVersionUrl = true;
options.EnableLogger = true;
```
---
## 响应格式
所有接口统一输出:
```json
{ "code": 200, "message": "成功", "data": { ... } }
```
HTTP 状态码**始终 200**,错误信息在 `code` 字段。
```csharp
// 无数据
return new SimApiBaseResponse();
return new SimApiBaseResponse(400, "参数错误");
return new SimApiBaseResponse(404); // 自动映射消息
// 带数据
return new SimApiBaseResponse<T>(data);
// 分页
return new SimApiBaseResponse<PageResponse<List<T>>>(new PageResponse<List<T>>
{
List = items, Page = 1, Count = 20, Total = 100
});
```
| 控制器返回值 | JSON 输出 |
|-------------|----------|
| `null` | `{"code":200,"message":"成功"}` |
| 普通对象 | `{"code":200,"message":"成功","data":对象}` |
| `SimApiBaseResponse` | 原样 |
| `[OriginResponse]` 方法 | 完全不封装 |
---
## SimApiBaseController
```csharp
[ApiController]
[Route("[controller]")]
public class XxxController : SimApiBaseController { }
// 错误方法(protected static
Error(code, message) // 直接抛出,默认(500,"")
ErrorWhen(condition, code, message) // condition==true 抛出,默认(400,"")
ErrorWhenTrue(condition, code, message)// 同上别名
ErrorWhenFalse(condition, code, message)// condition==false 抛出,默认(400,"")
ErrorWhenNull(obj, code, message) // obj==null 抛出,默认(404,"请求的资源不存在")
// 当前登录信息(需 EnableSimApiAuth
SimApiLoginItem? loginInfo = LoginInfo; // 从 HttpContext.Items["LoginInfo"] 取
```
---
## Attributes
### [SimApiAuth] — 认证
```csharp
[SimApiAuth] // 仅检查登录
[SimApiAuth("admin")] // Type 包含 "admin"
[SimApiAuth("admin,manager")] // 逗号分隔,OR 关系
```
### [SimApiDoc] — Swagger 注解
```csharp
[SimApiDoc("分组名", "接口名")]
[SimApiDoc("分组名", "接口名", "接口描述")]
[SimApiDoc(new[]{"tag1","tag2"}, "接口名")]
```
### [SynapseEvent] — MQTT 事件处理
```csharp
[SynapseEvent("order/created")]
public void OnOrderCreated(string eventName) { }
[SynapseEvent("order/+/status")] // 支持 + 和 # 通配符
public void OnOrderStatus(string eventName, MyDto data) { }
// 参数规则:0个、1个(string eventName)、2个(string eventName, T data)
```
### [SynapseRpc] — MQTT RPC 方法
```csharp
[SynapseRpc] // 方法名 = "ClassName.MethodName"
[SynapseRpc("customRpcName")] // 自定义名
// 支持 0~2 个参数,第2个固定为 Dictionary<string,string>headers
public UserDto GetUserInfo(GetUserRequest req) { }
public UserDto GetUserInfo(GetUserRequest req, Dictionary<string, string> headers) { }
```
### [AesBody] — AES 解密请求体
```csharp
[HttpPost]
public IActionResult Submit([AesBody(KeyProvider = typeof(MyAesKeyProvider))] MyRequest req) { }
// 客户端提交: {"data": "Base64(AES-256-CBC 加密 JSON)"}
```
### [OriginResponse] — 跳过响应封装
```csharp
[HttpGet][OriginResponse]
public string GetRaw() => "raw string";
```
### [SimApiSign] — API 签名验证
```csharp
[SimApiSign(KeyProvider = typeof(MySignProvider))]
public IActionResult SecureApi(...) { }
// 签名算法:MD5(field1=v1&...&appId=xxx&timestamp=ts&nonce=nnn&密钥)
```
---
## Auth 配置 & SimApiAuth 服务
```csharp
// Program.cs
options.EnableSimApiAuth = true;
options.RedisConfiguration = "..."; // 必须
// Token 通过 Header 传入:Token: <value>
```
```csharp
// SimApiLoginItem 结构
{ Id: string, Type: string[], Meta: Dictionary<string,string>, Extra: object? }
// DI 注入使用
public MyController(SimApiAuth auth) { }
string token = auth.Login(loginItem); // 自动生成 GUID token
string token = auth.Login(loginItem, "custom-token");
auth.Update(loginItem, token);
SimApiLoginItem? info = auth.GetLogin(token);
auth.Logout(token);
```
自动路由(`EnableSimApiAuth` 开启后):
- `POST /auth/check` — 检测登录状态
- `POST /auth/logout` — 退出登录
- `POST /user/info` — 获取用户信息(需登录)
---
## Swagger 配置(EnableSimApiDoc
```csharp
options.ConfigureSimApiDoc(doc =>
{
doc.DocumentTitle = "接口文档";
doc.ApiGroups = [
new("api", "公共接口"),
new("admin", "管理接口", "描述可选")
];
doc.ApiAuth = new SimApiAuthOption { Type = ["SimApiAuth"] };
doc.SupportedMethod = [SubmitMethod.Post]; // 默认仅 POST
});
// 分组方式:控制器或方法加 [ApiExplorerSettings(GroupName = "admin")]
// 不加则默认归入 Id="api" 的分组
```
---
## 对象存储(EnableSimApiStorage
```csharp
options.ConfigureSimApiStorage(s =>
{
s.Endpoint = "http://minio:9000"; // 不能以 / 结尾
s.AccessKey = "admin";
s.SecretKey = "pass";
s.Bucket = "my-bucket";
s.ServeUrl = "http://cdn.example.com/my-bucket"; // 不能以 / 结尾
});
```
```csharp
// DI 注入
public MyController(SimApiStorage storage) { }
// 路径必须以 / 开头
GetUploadUrlResponse r = storage.GetUploadUrl("/avatars/user1.jpg");
// r.UploadUrl → 前端 PUT 上传地址;r.DownloadUrl → 公开访问 URLr.Path → 相对路径
string url = storage.GetDownloadUrl("/files/doc.pdf"); // 默认 10 分钟
string url = storage.GetDownloadUrl("/files/doc.pdf", expire: 3600);
storage.UploadFile("/path/file.jpg", stream, "image/jpeg"); // 服务端直传
string? url = storage.FullUrl("/path/file"); // 路径转完整 URL
string? url = storage.GetUrl("/path/file"); // 同上
string? path = storage.GetPath("http://cdn.../my-bucket/path/file"); // URL 转路径
IMinioClient mc = storage.Client; // 暴露底层 MinIO 客户端
```
---
## 任务调度(EnableJob
```csharp
options.ConfigureSimApiJob(job =>
{
job.DashboardUrl = "/jobs"; // null 则不开启 Dashboard
job.DashboardAuthUser = "admin";
job.DashboardAuthPass = "Admin@123!";
job.RedisConfiguration = null; // null 则使用全局 RedisConfiguration
job.Database = 1; // Redis DB 编号,null 用默认
job.Servers = [
new SimApiJobServerConfig { Queues = ["default"], WorkerNum = 5 }, // 默认 WorkerNum=5
new SimApiJobServerConfig { Queues = ["email"], WorkerNum = 2 }
];
});
```
```csharp
BackgroundJob.Enqueue(() => myService.DoWork());
BackgroundJob.Schedule(() => myService.DoWork(), TimeSpan.FromMinutes(5));
RecurringJob.AddOrUpdate("job-id", () => myService.DoWork(), Cron.Daily);
var id = BackgroundJob.Enqueue(() => Step1());
BackgroundJob.ContinueJobWith(id, () => Step2());
```
---
## MQTT 通信(EnableSynapse
```csharp
options.ConfigureSimApiSynapse(s =>
{
s.Websocket = "ws://mqtt:8083/mqtt"; // WebSocket 连接
s.Username = "user";
s.Password = "pass";
s.SysName = "my-system"; // Topic 命名空间前缀
s.AppName = "order-service"; // 服务名
s.AppId = "instance-001"; // 实例ID,不填自动 GUID
s.RpcTimeout = 3; // RPC 超时秒数
s.EventLoadBalancing = false; // $queue 订阅负载均衡
s.EnableConfigStore = true; // 分布式配置中心
s.DisableEventClient = false;
s.DisableRpcClient = false;
});
```
Topic 规则:
```
事件发布: {SysName}/event/{AppName}/{eventName}
事件订阅: {SysName}/event/{eventName}(或 $queue/... 启用负载均衡)
RPC 请求: {SysName}/{targetApp}/rpc/server/{method}
RPC 响应: {SysName}/{callerApp}/rpc/client/{AppId}/{messageId}
配置存储: {SysName}/synapse-config-store/{key}Retain
```
```csharp
// DI 注入
public MyService(Synapse synapse) { }
synapse.Event("order/created", new { OrderId = 1 }); // 发布事件
// RPC 调用(同步,返回 SimApiBaseResponse<T>
var res = synapse.Rpc<UserDto>("user-service", "GetUserInfo", new { Id = 1 });
var res = synapse.Rpc<UserDto>("user-service", "GetUserInfo", param,
headers: new Dictionary<string, string> { { "traceId", "xxx" } });
// code=502 表示 RPC 超时
// 分布式配置
synapse.SetConfig("key", "value");
string? val = synapse.GetConfig("key");
synapse.OnConfigChanged += (sender, item) => Console.WriteLine($"{item.Key}={item.Value}");
// RPC 方法内部抛错
synapse.RpcError(400, "参数错误");
synapse.RpcErrorWhen(id <= 0, 400, "ID 无效");
```
处理器类(含 `[SynapseRpc]`/`[SynapseEvent]` 的类无需手动注册,自动扫描为 Scoped):
```csharp
public class OrderEventHandler
{
[SynapseEvent("order/+/status")]
public void OnOrderStatus(string eventName, OrderStatusDto data) { }
}
public class UserRpcService
{
[SynapseRpc] // 注册为 "UserRpcService.GetUserInfo"
public UserDto GetUserInfo(GetUserRequest req) { return ...; }
[SynapseRpc("customName")]
public ResultDto DoSomething(RequestDto req, Dictionary<string, string> headers) { }
}
```
---
## API 签名验证([SimApiSign]
```csharp
// 1. 实现密钥提供者
public class MySignProvider : SimApiSignProviderBase
{
public override string? AppIdName { get; set; } = "appId";
public override string TimestampName { get; set; } = "timestamp";
public override string NonceName { get; set; } = "nonce";
public override string SignName { get; set; } = "sign";
public override int QueryExpires { get; set; } = 5;
public override bool DuplicateRequestProtection { get; set; } = true;
public override string[] SignFields { get; set; } = ["userId"]; // 额外签名字段
public override string? GetKey(string? appId)
{
// 根据 appId 返回密钥
return db.Apps.Find(appId)?.SecretKey;
}
}
services.AddScoped<MySignProvider>(); // 注册
// 2. 使用
[SimApiSign(KeyProvider = typeof(MySignProvider))]
public IActionResult SecureApi(...) { }
```
---
## AES 加密传输([AesBody]
算法:**AES-256-CBC + PKCS7**IV 随机生成附在密文前,整体 Base64 编码。
```csharp
// 1. 实现密钥提供者
public class MyAesKeyProvider : AesBodyProviderBase
{
public override string? AppIdName { get; set; } = "appId"; // 从 Query/Header 取
public override string? GetKey(string? appId) => db.Apps.Find(appId)?.SecretKey;
}
services.AddScoped<MyAesKeyProvider>();
// 2. 使用(客户端提交 {"data": "Base64密文"}
[HttpPost]
public IActionResult Submit([AesBody(KeyProvider = typeof(MyAesKeyProvider))] MyRequest req) { }
// 工具类(静态,无需注入)
string cipher = SimApiAesUtil.Encrypt("明文", "任意长度密钥"); // SHA256 处理为 32 字节
string plain = SimApiAesUtil.Decrypt(cipher, "任意长度密钥");
```
---
## Redis 缓存(SimApiCache
> 依赖 `RedisConfiguration`key 自动加前缀 `SimApi:Cache:`
```csharp
public MyService(SimApiCache cache) { }
cache.Set("key", value); // 永不过期
cache.Set("key", value, new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
string? raw = cache.Get("key"); // 原始字符串
int? val = cache.Get<int>("key"); // 反序列化
```
---
## HTTP 客户端(SimApiHttpClient
```csharp
var client = new SimApiHttpClient(appId: "myapp", appKey: "secret")
{
Server = "https://api.example.com",
AppIdName = "appId",
TimestampName = "timestamp",
NonceName = "nonce",
SignName = "sign",
SignFields = ["field1"]
};
var r = client.SignQuery<T>("/api/user", body, queries); // 仅签名
var r = client.AesQuery<T>("/api/user", body); // 仅 AES 加密
var r = client.AesSignQuery<T>("/api/user", body, queries);// AES + 签名
```
---
## 工具类(SimApiUtil,全部静态)
```csharp
DateTime cst = SimApiUtil.CstNow; // UTC+8 当前时间
double ts = SimApiUtil.TimestampNow; // 秒级 Unix 时间戳
string simVer = SimApiUtil.SimApiVersion; // SimApi 包版本
string appVer = SimApiUtil.AppVersion; // 宿主应用版本
string md5 = SimApiUtil.Md5("src"); // 32位 MD5
string md5 = SimApiUtil.Md5("src", "x3"); // 48位
string sha1 = SimApiUtil.Sha1("src");
string json = SimApiUtil.Json(obj); // camelCase,中文不转义
T obj = SimApiUtil.XmlDeserialize<T>(xml);
JsonSerializerOptions opts = SimApiUtil.JsonOption;
bool ok = SimApiUtil.CheckCell("13800138000"); // 手机号验证
// IQueryable 扩展
var paged = dbContext.Users.AsQueryable().Paginate(page: 1, count: 20);
```
---
## 数据模型基类(SimApiBaseModel
```csharp
public class UserEntity : SimApiBaseModel
{
public string Name { get; set; }
// 自动字段:Id(GUID string)、CreatedAt、UpdatedAt
}
entity.MapData(dto); // 跳过 Id/CreatedAt/UpdatedAt
entity.MapData(dto, mapAll: true); // 映射所有字段
entity.MapData(dto, new[]{"Name","Email"}); // 只映射指定字段
entity.UpdateTime(); // 手动更新 UpdatedAt
// 注意:只映射同名+同类型+源值不为null 的属性
```
---
## Coce 统一身份(EnableCoceSdk
> 同时需要 `EnableSimApiAuth = true`
```csharp
options.ConfigureCoceSdk(coce =>
{
coce.ApiEndpoint = "https://api.coce.cc"; // 默认
coce.AuthEndpoint = "https://home.coce.cc"; // 默认
coce.AppId = "your-app-id";
coce.AppKey = "your-app-key";
});
```
```csharp
// DI 注入
public MyService(CoceApp coce) { }
// 用户
coce.GetUserInfo(levelToken)
coce.GetUserGroups(levelToken)
coce.SearchUserByPhone("13800138000")
coce.SearchUserByIds(new[]{"uid1","uid2"})
// 消息
coce.SendUserMessage(userId, "标题", "内容")
// 支付
string? tradeNo = coce.TradeCreate("商品名", 100, "扩展数据")
coce.TradeCheck(tradeNo)
coce.TradeRefund(tradeNo)
// Token
coce.GetLevelToken(lv1Token, level: 5)
coce.SaveToken(userId, levelToken)
coce.GetToken(userId)
// 代理请求
coce.ProxyQuery<T>(uri, token)
coce.ProxyQuery<T>(uri, token, json)
coce.ProxyQueue<T>(uri, token, data)
```
自动路由:
- `POST /auth/login` — Coce 一键登录(前端传 `{"data":"lv1Token"}`
- `POST /user/groups` — 获取用户群组(需登录)
- `GET /auth/config` — 获取 AppId 和授权 URL
自定义登录逻辑:
```csharp
public class MyLoginProcessor : ICoceLoginProcessor
{
public SimApiLoginItem Process(SimApiLoginItem item, GroupInfo[] groups)
{
if (groups.Any(g => g.Role == "owner"))
item.Type = ["user", "admin"];
return item;
}
}
services.AddScoped<ICoceLoginProcessor, MyLoginProcessor>();
```
---
## 内置路由汇总
| 路由 | 方法 | 条件 |
|------|------|------|
| `/swagger` | GET | `EnableSimApiDoc` |
| `/versions` | GET/POST | `EnableVersionUrl`(默认开) |
| `/auth/check` | POST | `EnableSimApiAuth` |
| `/auth/logout` | POST | `EnableSimApiAuth` |
| `/user/info` | POST | `EnableSimApiAuth`(需登录) |
| `/auth/login` | POST | `EnableCoceSdk` |
| `/user/groups` | POST | `EnableCoceSdk`(需登录) |
| `/auth/config` | GET | `EnableCoceSdk` |
| `/jobs` | GET | `EnableJob` |
---
## 异常处理流程
```
请求进入
└─ SimApiExceptionMiddleware(捕获所有异常 → HTTP 200 + code 字段)
└─ SimApiAuthMiddleware(解析 Token
└─ [SimApiSign] Filter
└─ [SimApiAuth] Filter
└─ OnActionExecuting(模型验证 → code 400
└─ Action 执行
└─ SimApiResponseFilter(封装响应)
```
+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;
}
}
+8
View File
@@ -0,0 +1,8 @@
using System;
namespace SimApi.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public class OriginResponseAttribute : Attribute
{
}
+5 -10
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,21 +34,16 @@ 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"];
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
//检测是否登录
if (loginInfo == null)
{
throw new SimApiException(401);
}
if (Types == null) return;
//检测用户类型
if (!Types.Intersect(loginInfo.Type).Any())
{
+18 -3
View File
@@ -12,13 +12,28 @@ public class SimApiDocAttribute : SwaggerOperationAttribute
/// <summary>
/// 定义接口说明
/// </summary>
/// <param name="tag">接口分组</param>
/// <param name="tags">接口分组列表</param>
/// <param name="name">接口名称</param>
public SimApiDocAttribute(string tag, string name)
/// <param name="description">接口描述</param>
public SimApiDocAttribute(string[] tags, string name, string? description = null)
{
Tags = new[] { tag };
Tags = tags;
Summary = name;
if (description != null)
{
Description = description;
}
// Consumes = new[] {"application/json"};
// Produces = new[] {"application/json"};
}
/// <summary>
/// 定义接口说明
/// </summary>
/// <param name="tag">接口分组</param>
/// <param name="name">接口名称</param>
/// <param name="description">接口描述</param>
public SimApiDocAttribute(string tag, string name, string? description = null) : this([tag], name, description)
{
}
}
+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 -7
View File
@@ -3,12 +3,7 @@ using System;
namespace SimApi.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public class SynapseEventAttribute : Attribute
public class SynapseEventAttribute(string? name = null) : Attribute
{
public string Name { get; }
public SynapseEventAttribute(string name)
{
Name = name;
}
public string? Name { get; } = name;
}
+1 -1
View File
@@ -5,7 +5,7 @@ namespace SimApi.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public class SynapseRpcAttribute : Attribute
{
public string Name { get; }
public string? Name { get; }
public SynapseRpcAttribute()
{
+235
View File
@@ -0,0 +1,235 @@
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Helpers;
namespace SimApi.CoceSdk;
public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache)
{
/// <summary>
/// 获取Level Token
/// </summary>
/// <param name="lv1Token"></param>
/// <param name="level"></param>
/// <returns></returns>
public LevelTokenResponse? GetLevelToken(string lv1Token, int level = 5)
{
var dict = new Dictionary<string, object>
{
{ "lv1Token", lv1Token },
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "level", level }
};
return QueryAppApi<LevelTokenResponse>("/api/app/token", dict);
}
/// <summary>
/// 通过用户手机号搜索用户
/// </summary>
/// <param name="phone"></param>
/// <returns></returns>
public UserInfo? SearchUserByPhone(string phone)
{
var dict = new Dictionary<string, object>
{
{ "cell", phone },
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
};
return QueryAppApi<UserInfo>("/api/app/user/search-by-phone", dict);
}
/// <summary>
/// 通过给出的UserId列表获取用户信息
/// </summary>
/// <param name="userIds"></param>
/// <returns></returns>
public UserInfo[]? SearchUserByIds(IEnumerable<string> userIds)
{
var dict = new Dictionary<string, object>
{
{ "ids", string.Join(",", userIds) },
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
};
return QueryAppApi<UserInfo[]>("/api/app/user/search-by-ids", dict);
}
/// <summary>
/// 向用户发送消息
/// </summary>
/// <param name="userId"></param>
/// <param name="title"></param>
/// <param name="content"></param>
/// <returns></returns>
public bool SendUserMessage(string userId, string title, string content)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "userId", userId },
{ "type", "text" },
{ "title", title },
{ "text", content }
};
return QueryAppApiNoResp("/api/app/message", dict);
}
/// <summary>
/// 创建交易订单号
/// </summary>
/// <param name="name"></param>
/// <param name="amount"></param>
/// <param name="ext"></param>
/// <returns></returns>
public string? TradeCreate(string name, int amount, string ext)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "amount", amount },
{ "ext", ext },
{ "name", name }
};
return QueryAppApi<string>("/api/app/trade/create", dict);
}
/// <summary>
/// 查询订单状态
/// </summary>
/// <param name="tradeNo"></param>
/// <returns></returns>
public CheckTradeResponse? TradeCheck(string tradeNo)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "tradeNo", tradeNo }
};
return QueryAppApi<CheckTradeResponse>("/api/app/trade/result", dict);
}
/// <summary>
/// 对订单进行退款
/// </summary>
/// <param name="tradeNo"></param>
/// <returns></returns>
public bool TradeRefund(string tradeNo)
{
var dict = new Dictionary<string, object>
{
{ "time", (int)SimApiUtil.TimestampNow },
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
{ "tradeNo", tradeNo }
};
return QueryAppApiNoResp("/api/app/trade/refund", dict);
}
private T? QueryAppApi<T>(string endpoint, Dictionary<string, object> request)
{
var response = QueryAppApi(endpoint, request);
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
if (result.Code == 200) return result.Data;
logger.LogDebug("发生错误: {Code} => {Message}", result.Code, result.Message);
return default;
}
private bool QueryAppApiNoResp(string endpoint, Dictionary<string, object> request)
{
var response = QueryAppApi(endpoint, request);
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse>().Result!;
return result.Code == 200;
}
private HttpResponseMessage QueryAppApi(string endpoint, Dictionary<string, object> request)
{
var platUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + endpoint;
var sorted = request.OrderBy(x => x.Key);
var signStr = sorted.Aggregate("", (current, item) => current + $"{item.Key}={item.Value}&").TrimEnd('&');
logger.LogDebug("签名的字符串: {SignStr}", signStr);
var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey);
logger.LogDebug("签名: {Sign}", sign);
request.Add("sign", sign);
logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, JsonSerializer.Serialize(request));
var http = new HttpClient();
return http.PostAsJsonAsync(platUrl, request).Result;
}
/// <summary>
/// 获取用户的群组信息
/// </summary>
/// <param name="token">Level >=2 的Token</param>
/// <returns></returns>
public IEnumerable<GroupInfo>? GetUserGroups(string token)
{
const string uri = "/api/lv2/user/groups";
var resp = ProxyQuery<GroupInfo[]>(uri, token,"{}");
return resp;
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public UserInfo? GetUserInfo(string token)
{
const string uri = "/api/lv1/user/info";
return ProxyQuery<UserInfo>(uri, token);
}
public void SaveToken(string userId, string levelToken)
{
cache.SetString($"LEVEL:TOKEN:{userId}", levelToken);
}
public string? GetToken(string userId)
{
return cache.GetString($"LEVEL:TOKEN:{userId}");
}
public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json);
public dynamic? ProxyQueue(string uri, string token, object data) =>
ProxyQuery<dynamic>(uri, token, JsonSerializer.Serialize(data));
public T? ProxyQueue<T>(string uri, string token, object data) =>
ProxyQuery<T>(uri, token, JsonSerializer.Serialize(data));
public T? ProxyQuery<T>(string uri, string token, string json = "{}")
{
var http = new HttpClient();
http.DefaultRequestHeaders.Add("Token", token);
var realUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + uri;
var response = http.PostAsync(realUrl, new StringContent(json, Encoding.UTF8, "application/json"))
.Result;
var resp = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
if (resp.Code != 200)
{
logger.LogDebug("请求发生错误: {RespCode} => {RespMessage}", resp.Code, resp.Message);
}
return resp.Code == 200 ? resp.Data : default;
}
public ConfigResponse GetConfig()
{
return new ConfigResponse(simApiOptions.CoceSdkOptions.AppId!, simApiOptions.CoceSdkOptions.AuthEndpoint);
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace SimApi.CoceSdk;
public class CoceAppSdkOption
{
/**
* 中心API服务器地址
*/
public string ApiEndpoint { get; set; } = "https://api.coce.cc";
public string AuthEndpoint { get; set; } = "https://home.coce.cc";
public string? AppId { get; set; }
public string? AppKey { get; set; }
}
+51
View File
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Controllers;
using SimApi.Helpers;
namespace SimApi.CoceSdk;
public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp) : SimApiBaseController
{
[HttpPost]
public SimApiBaseResponse<ConfigResponse> GetConfig()
{
return new SimApiBaseResponse<ConfigResponse>(coce.GetConfig());
}
[HttpPost]
public SimApiBaseResponse<string> Login([FromBody] SimApiOneFieldRequest<string> request)
{
var data = coce.GetLevelToken(request.Data!);
ErrorWhenNull(data, 400);
coce.SaveToken(data!.UserId, data.Token);
var userinfo = coce.GetUserInfo(data!.Token);
var meta = new Dictionary<string, string>
{
{ "name", userinfo!.Name },
{ "image", userinfo.Image }
};
var groups = coce.GetUserGroups(data.Token!)!;
var loginItem = new SimApiLoginItem
{
Id = data.UserId,
Meta = meta,
};
var processor = sp.GetService<ICoceLoginProcessor>();
processor?.Process(loginItem, groups.ToArray());
return new SimApiBaseResponse<string>(auth.Login(loginItem));
}
[HttpPost, SimApiAuth]
public SimApiBaseResponse<GroupInfo[]> ListGroups()
{
var levelToken = coce.GetToken(LoginInfo.Id!);
var groups = coce.GetUserGroups(levelToken!)!;
return new SimApiBaseResponse<GroupInfo[]>(groups.ToArray());
}
}
+43
View File
@@ -0,0 +1,43 @@
using System;
namespace SimApi.CoceSdk;
public record ConfigResponse(string AppId, string AuthUrl);
public record LevelTokenResponse(string Token, string UserId, int TokenLevel);
public record GroupInfo(string Id, string Name, string Image, string Description, string Role);
public record UserInfo(string UserId, string Name, string Image);
public record CheckTradeResponse(
string TradeNo,
int Amount,
int Fee,
string Name,
string? Ext,
string Status,
DateTime CreatedAt,
DateTime? FinishedAt,
DateTime? RefundAt,
DateTime? CloseAt);
public class UserInfoWithGroup
{
public string? UserId { get; set; }
public string? Name { get; set; }
public string? LevelToken { get; set; }
public UserGroupItem[]? UserGroupItems { get; set; }
}
public class UserGroupItem
{
public string? GroupId { get; set; }
public string? GroupName { get; set; }
public string? GroupRole { get; set; }
}
+9
View File
@@ -0,0 +1,9 @@
using System.Collections.Generic;
using SimApi.Communications;
namespace SimApi.CoceSdk;
public interface ICoceLoginProcessor
{
SimApiLoginItem Process(SimApiLoginItem loginItem, GroupInfo[] groups);
}
+6 -8
View File
@@ -1,13 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace SimApi.Communications;
namespace SimApi.Communications;
/// <summary>
/// 只有ID的请求
/// </summary>
public class SimApiIdOnlyRequest
{
[Required] public int Id { get; set; }
public required int Id { get; set; }
}
/// <summary>
@@ -15,7 +13,7 @@ public class SimApiIdOnlyRequest
/// </summary>
public class SimApiStringIdOnlyRequest
{
[Required] public string Id { get; set; }
public required string Id { get; set; }
}
/// <summary>
@@ -24,7 +22,7 @@ public class SimApiStringIdOnlyRequest
/// <typeparam name="T"></typeparam>
public class SimApiOneFieldRequest<T>
{
[Required] public T Data { get; set; }
public required T Data { get; set; }
}
/// <summary>
@@ -32,6 +30,6 @@ public class SimApiOneFieldRequest<T>
/// </summary>
public class SimApiBasePageRequest
{
[Required] public int Page { get; set; }
[Required] public int Count { get; set; }
public required int Page { get; set; }
public required int Count { get; set; }
}
+10 -21
View File
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using SimApi.Helpers;
namespace SimApi.Communications;
@@ -12,6 +13,10 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
public int Code { get; set; } = code;
public string Message { get; set; } = message;
public SimApiBaseResponse() : this(200, "成功")
{
}
/// <summary>
/// 默认错误代码对应提示信息
/// </summary>
@@ -36,36 +41,20 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
/// <returns></returns>
public override string ToString()
{
return JsonSerializer.Serialize(this, new JsonSerializerOptions
{
IgnoreReadOnlyProperties = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters =
{
new JsonStringEnumConverter()
}
});
return SimApiUtil.Json(this);
}
}
/// <summary>
/// 动态内容分页
/// 分页内容返回
/// </summary>
/// <typeparam name="T"></typeparam>
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
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; }
public SimApiBasePageResponse(T list, int page, int count, int total) : this()
{
List = list;
Page = page;
Count = count;
Total = total;
}
}
/// <summary>
@@ -74,7 +63,7 @@ public class SimApiBasePageResponse<T>() : SimApiBaseResponse
/// <typeparam name="T"></typeparam>
public class SimApiBaseResponse<T>() : SimApiBaseResponse
{
public T Data { get; set; }
public T? Data { get; set; }
public SimApiBaseResponse(T data) : this()
{
+7 -1
View File
@@ -5,4 +5,10 @@ namespace SimApi.Communications;
/// <summary>
/// 登录信息中间件
/// </summary>
public record SimApiLoginItem(string Id, string[] Type,Dictionary<string,string> Meta = null);
public class SimApiLoginItem
{
public required string Id { get; set; }
public string[] Type { get; set; } = ["user"];
public Dictionary<string, string> Meta { get; set; } = [];
public object? Extra { get; set; }
};
+14 -19
View File
@@ -6,22 +6,22 @@ namespace SimApi.Configurations;
/// <summary>
/// 文档组配置
/// </summary>
public class SimApiDocGroupOption
public class SimApiDocGroupOption(string id, string name, string description = "")
{
/// <summary>
/// 文档标识
/// </summary>
public string Id { get; set; }
public string Id { get; set; } = id;
/// <summary>
/// 文档名称
/// </summary>
public string Name { get; set; }
public string Name { get; set; } = name;
/// <summary>
/// 文档描述
/// </summary>
public string Description { get; set; }
public string Description { get; set; } = description!;
}
/// <summary>
@@ -29,15 +29,15 @@ public class SimApiDocGroupOption
/// </summary>
public class SimApiAuthOption
{
public string[] Type { get; set; } = new[] { "SimApiAuth" };
public string[] Type { get; set; } = ["SimApiAuth"];
public string Description { get; set; } = "认证服务器颁发的AccessToken";
public string AuthorizationUrl { get; set; }
public string AuthorizationUrl { get; set; } = null!;
public string TokenUrl { get; set; }
public string TokenUrl { get; set; } = null!;
public Dictionary<string, string> Scopes { get; set; }
public Dictionary<string, string> Scopes { get; set; } = null!;
}
/// <summary>
@@ -48,20 +48,15 @@ public class SimApiDocOptions
/// <summary>
/// 文档组配置
/// </summary>
public SimApiDocGroupOption[] ApiGroups { get; set; } = new[]
{
new SimApiDocGroupOption
{
Id = "api",
Name = "Api",
Description = "Api接口文档"
}
};
public SimApiDocGroupOption[] ApiGroups { get; set; } =
[
new("api", "Api", "Api接口文档")
];
/// <summary>
/// 授权配置
/// </summary>
public SimApiAuthOption ApiAuth { get; set; } = new SimApiAuthOption();
public SimApiAuthOption ApiAuth { get; set; } = new();
/// <summary>
/// 文档页面标题
@@ -71,5 +66,5 @@ public class SimApiDocOptions
/// <summary>
/// 接口支持的调用方式
/// </summary>
public SubmitMethod[] SupportedMethod { get; set; } = new[] { SubmitMethod.Post };
public SubmitMethod[] SupportedMethod { get; set; } = [SubmitMethod.Post];
}
+40
View File
@@ -0,0 +1,40 @@
namespace SimApi.Configurations;
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()];
}
public class SimApiJobServerConfig()
{
public string[] Queues { get; set; } = ["default"];
public int WorkerNum { get; set; } = 5;
}
+63 -22
View File
@@ -1,26 +1,53 @@
using System;
using SimApi.CoceSdk;
namespace SimApi.Configurations;
public class SimApiOptions
{
public string? RedisConfiguration { get; set; }
/// <summary>
/// 是否启用后台任务系统 *基于Hangfire
/// </summary>
public bool EnableJob { get; set; }
/// <summary>
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
/// default: false
/// </summary>
public bool EnableSimApiAuth { get; set; }
/// <summary>
/// 是否使用CoceSdk
/// </summary>
public bool EnableCoceSdk { get; set; }
/// <summary>
/// 开启S3兼容的存储系统。
/// default: false
/// </summary>
public bool EnableSimApiStorage { get; set; }
/// <summary>
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
/// default: false
/// </summary>
public bool EnableSimApiDoc { get; set; }
/// <summary>
/// 是否启用Synapse
/// </summary>
public bool EnableSynapse { get; set; }
/// <summary>
/// 启用全部Cors,对于开发前后分离的时候很有用。
/// default: true
/// </summary>
public bool EnableCors { get; set; } = true;
/// <summary>
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
/// default: false
/// </summary>
public bool EnableSimApiAuth { get; set; } = false;
/// <summary>
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
/// default: false
/// </summary>
public bool EnableSimApiDoc { get; set; } = false;
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
/// <summary>
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
@@ -29,10 +56,10 @@ public class SimApiOptions
public bool EnableSimApiException { get; set; } = true;
/// <summary>
/// 开启S3兼容的存储系统。
/// default: false
/// 启用返回结果拦截
/// </summary>
public bool EnableSimApiStorage { get; set; } = false;
public bool EnableSimApiResponseFilter { get; set; } = true;
/// <summary>
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
@@ -46,17 +73,26 @@ public class SimApiOptions
/// </summary>
public bool EnableLowerUrl { get; set; } = true;
/// <summary>
/// 应用可以通过 /versions 显示出应用版本和SimApi包版本
/// default: true
/// </summary>
public bool EnableVersionUrl { get; set; } = true;
/// <summary>
/// 启用格式化的 Console Logger
/// default: false
/// </summary>
public bool EnableLogger { get; set; } = false;
public bool EnableLogger { get; set; } = true;
/// <summary>
/// 是否启用Synapse
/// 配置Job
/// </summary>
public bool EnableSynapse { get; set; } = false;
public SimApiJobOptions SimApiJobOptions { get; set; } = new();
/// <summary>
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
@@ -70,23 +106,28 @@ public class SimApiOptions
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions> options = null)
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
{
options?.Invoke(SimApiSynapseOptions);
}
public void ConfigureSimApiSynapse(SimApiSynapseOptions options)
public void ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)
{
SimApiSynapseOptions = options;
options?.Invoke(CoceSdkOptions);
}
public void ConfigureSimApiDoc(Action<SimApiDocOptions> options = null)
public void ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)
{
options?.Invoke(SimApiDocOptions);
}
public void ConfigureSimApiStorage(Action<SimApiStorageOptions> options = null)
public void ConfigureSimApiStorage(Action<SimApiStorageOptions>? options = null)
{
options?.Invoke(SimApiStorageOptions);
}
public void ConfigureSimApiJob(Action<SimApiJobOptions>? options = null)
{
options?.Invoke(SimApiJobOptions);
}
}
+5 -5
View File
@@ -5,19 +5,19 @@ public class SimApiStorageOptions
/// <summary>
/// S3 服务器入口地址
/// </summary>
public string Endpoint { get; set; }
public string? Endpoint { get; set; }
/// <summary>
/// S3 服务器文件访问地址
/// </summary>
public string ServeUrl { get; set; }
public string? ServeUrl { get; set; }
/// <summary>
/// S3服务 Bucket
/// </summary>
public string Bucket { get; set; }
public string? Bucket { get; set; }
public string AccessKey { get; set; }
public string? AccessKey { get; set; }
public string SecretKey { get; set; }
public string? SecretKey { get; set; }
}
+16 -21
View File
@@ -2,29 +2,24 @@ namespace SimApi.Configurations;
public class SimApiSynapseOptions
{
public string MqHost { get; set; }
public int MqPort { get; set; }
public string MqUser { get; set; }
public string MqPass { get; set; }
public string MqVHost { get; set; } = "/";
public string SysName { get; set; }
public string AppName { get; set; }
public string AppId { get; set; }
/// <summary>
/// Mqtt服务器的Websocket地址
/// </summary>
public string? Websocket { get; set; }
public string? Username { get; set; }
public string? Password { get; set; }
public string? SysName { get; set; }
public string? AppName { get; set; }
public string? AppId { get; set; }
public int RpcTimeout { get; set; } = 3;
public ushort EventProcessorNum { get; set; } = 20;
public ushort RpcProcessorNum { get; set; } = 20;
/// <summary>
/// Event是否使用负载均衡
/// 也就是订阅$queue主题,消息会分发给不同的AppId
/// 如果false,多个AppId都可以同时收到消息
/// </summary>
public bool EventLoadBalancing { get; set; } = false;
public bool EnableConfigStore { get; set; } = true;
public bool DisableEventClient { get; set; } = false;
public bool DisableRpcClient { get; set; } = false;
}
+49
View File
@@ -0,0 +1,49 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.Controllers;
public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
{
/// <summary>
/// 检测用户登陆的控制器
/// </summary>
/// <returns></returns>
[HttpPost, SimApiDoc("认证", "检测登陆")]
public SimApiBaseResponse<string> CheckLogin()
{
ErrorWhenNull(LoginInfo, 401, "未登录");
return new SimApiBaseResponse<string>
{
Data = LoginInfo.Id
};
}
/// <summary>
/// 退出登陆
/// </summary>
/// <returns></returns>
[HttpPost, SimApiDoc("认证", "退出登陆")]
public SimApiBaseResponse Logout()
{
string? token = null;
if (Request.Headers.TryGetValue("Token", out var value))
{
token = value;
}
auth.Logout(token!);
return new SimApiBaseResponse();
}
[HttpPost, SimApiAuth]
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
{
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
}
}
+15 -13
View File
@@ -1,4 +1,5 @@
using SimApi.Communications;
using System.Diagnostics.CodeAnalysis;
using SimApi.Communications;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
@@ -13,12 +14,15 @@ namespace SimApi.Controllers;
/// 2. 报错返回
/// 3. 错误回馈页面
/// </summary>
///
[Consumes("application/json")]
[Produces("application/json")]
public class SimApiBaseController : Controller
{
/// <summary>
/// 当前登录用户的ID
/// </summary>
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"];
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
/// <summary>
/// 验证请求参数
@@ -26,14 +30,12 @@ public class SimApiBaseController : Controller
/// <param name="context"></param>
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
if (context.ModelState.IsValid) return;
foreach (var item in context.ModelState.Values.Where(item =>
item.ValidationState == ModelValidationState.Invalid))
{
foreach (var item in context.ModelState.Values.Where(item =>
item.ValidationState == ModelValidationState.Invalid))
{
Error(400, item.Errors.First().ErrorMessage);
break;
}
Error(400, item.Errors.First().ErrorMessage);
break;
}
}
@@ -55,7 +57,7 @@ public class SimApiBaseController : Controller
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhen(bool condition, int code = 400, string message = "")
protected static void ErrorWhen([DoesNotReturnIf(true)] bool condition, int code = 400, string message = "")
{
if (condition)
{
@@ -70,7 +72,7 @@ public class SimApiBaseController : Controller
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenTrue(bool condition, int code = 400, string message = "")
protected static void ErrorWhenTrue([DoesNotReturnIf(true)] bool condition, int code = 400, string message = "")
{
ErrorWhen(condition, code, message);
}
@@ -82,7 +84,7 @@ public class SimApiBaseController : Controller
/// <param name="condition"></param>
/// <param name="code"></param>
/// <param name="message"></param>
protected static void ErrorWhenFalse(bool condition, int code = 400, string message = "")
protected static void ErrorWhenFalse([DoesNotReturnIf(false)] bool condition, int code = 400, string message = "")
{
ErrorWhen(!condition, code, message);
}
@@ -93,7 +95,7 @@ public class SimApiBaseController : Controller
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenNull(object condition, int code = 404, string message = "请求的资源不存在")
protected static void ErrorWhenNull([NotNull] object? condition, int code = 404, string message = "请求的资源不存在")
{
ErrorWhen(condition == null, code, message);
}
+12 -37
View File
@@ -1,12 +1,11 @@
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.Controllers;
[ApiExplorerSettings(GroupName = "api")]
public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
public class SimApiCommonController : SimApiBaseController
{
/// <summary>
/// 错误回馈页面
@@ -20,41 +19,17 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
return new SimApiBaseResponse(code);
}
/// <summary>
/// 检测用户登陆的控制器
/// </summary>
/// <returns></returns>
[HttpPost("/auth/check"), SimApiDoc("认证", "检测登陆")]
public SimApiBaseResponse<string> CheckLogin()
[HttpPost, HttpGet]
public SimApiBaseResponse<Dictionary<string, string>> Versions()
{
ErrorWhenNull(LoginInfo, 401);
return new SimApiBaseResponse<string>
return new SimApiBaseResponse<Dictionary<string, string>>()
{
Data = LoginInfo.Id
Data = new Dictionary<string, string>
{
{ "SimApi", SimApiUtil.SimApiVersion },
{ "App", SimApiUtil.AppVersion }
}
};
}
/// <summary>
/// 退出登陆
/// </summary>
/// <returns></returns>
[HttpPost("/auth/logout"), SimApiDoc("认证", "退出登陆")]
public SimApiBaseResponse Logout()
{
string token = null;
if (Request.Headers.TryGetValue("Token", out var value))
{
token = value;
}
auth.Logout(token!);
return new SimApiBaseResponse();
}
[HttpPost("/logined"),SimApiAuth]
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
{
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
}
}
+119
View File
@@ -0,0 +1,119 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace SimApi.Helpers;
public static class SimApiAesUtil
{
// 密钥长度:256位 (32字节)
private const int KeySize = 256;
// 块大小:128位 (16字节)
private const int BlockSize = 128;
// 加密模式 - 重命名以避免与枚举类型冲突
private const CipherMode AesCipherMode = CipherMode.CBC;
// 填充模式 - 重命名以避免与枚举类型冲突
private const PaddingMode AesPaddingMode = PaddingMode.PKCS7;
/// <summary>
/// AES 加密
/// </summary>
/// <param name="plainText">明文</param>
/// <param name="key">字符串密钥(将被处理为256位)</param>
/// <returns>加密后的Base64字符串(包含IV</returns>
public static string Encrypt(string plainText, string key)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException(nameof(plainText));
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException(nameof(key));
// 处理密钥为指定长度
var keyBytes = ProcessKey(key);
// 生成随机IV
var iv = GenerateRandomIv();
using var aes = CreateAesProvider(keyBytes, iv);
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using var ms = new MemoryStream();
// 先写入IV,解密时需要用到
ms.Write(iv, 0, iv.Length);
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="cipherText">加密后的Base64字符串</param>
/// <param name="key">字符串密钥(与加密时相同)</param>
/// <returns>解密后的明文</returns>
public static string Decrypt(string cipherText, string key)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException(nameof(cipherText));
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException(nameof(key));
var cipherBytes = Convert.FromBase64String(cipherText);
// 从加密数据中提取IV
var iv = new byte[BlockSize / 8];
Array.Copy(cipherBytes, 0, iv, 0, iv.Length);
// 处理密钥为指定长度
var keyBytes = ProcessKey(key);
using var aes = CreateAesProvider(keyBytes, iv);
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using var ms = new MemoryStream(cipherBytes, iv.Length, cipherBytes.Length - iv.Length);
using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
using var sr = new StreamReader(cs);
return sr.ReadToEnd();
}
/// <summary>
/// 处理密钥为指定长度(256位)
/// </summary>
private static byte[] ProcessKey(string key)
{
// 使用SHA256哈希处理密钥,确保得到32字节(256位)的密钥
return SHA256.HashData(Encoding.UTF8.GetBytes(key));
}
/// <summary>
/// 生成随机初始化向量
/// </summary>
private static byte[] GenerateRandomIv()
{
using var aes = Aes.Create();
aes.BlockSize = BlockSize;
aes.GenerateIV();
return aes.IV;
}
/// <summary>
/// 创建并配置AES加密服务提供器
/// </summary>
private static Aes CreateAesProvider(byte[] key, byte[] iv)
{
var aes = Aes.Create();
aes.KeySize = KeySize;
aes.BlockSize = BlockSize;
aes.Mode = AesCipherMode;
aes.Padding = AesPaddingMode;
aes.Key = key;
aes.IV = iv;
return aes;
}
}
+12 -34
View File
@@ -1,6 +1,4 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
@@ -13,48 +11,28 @@ namespace SimApi.Helpers;
public class SimApiAuth(IDistributedCache cache)
{
/// <summary>
/// 产生一个Token记录并返回Token
/// 登录信息
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <param name="meta"></param>
/// <param name="loginItem"></param>
/// <param name="token"></param>
/// <returns></returns>
public string Login(string id, Dictionary<string, string>? meta = null, string type = "user", string? token = null)
public string Login(SimApiLoginItem loginItem, string? token = null)
{
return Login(id, meta, new[] { type }, token);
token ??= Guid.NewGuid().ToString();
cache.SetString(token, JsonSerializer.Serialize(loginItem));
return token;
}
/// <summary>
/// 产生一个Token并记录用户ID角色[多角色]
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <param name="meta"></param>
/// <param name="uuid"></param>
/// <returns></returns>
// ReSharper disable once MemberCanBePrivate.Global
public string Login(string id, Dictionary<string, string>? meta, string[] type, string? uuid = null)
{
uuid ??= Guid.NewGuid().ToString();
var loginItem = new SimApiLoginItem(id, type, meta);
cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
return uuid;
}
/// <summary>
/// 设置登录的Meta信息
/// 更新登陆信息
/// </summary>
/// <param name="loginItem"></param>
/// <param name="token"></param>
/// <param name="meta"></param>
/// <returns></returns>
public bool SetMeta(string token, Dictionary<string, string> meta)
public string Update(SimApiLoginItem loginItem, string token)
{
var login = GetLogin(token);
if (login == null) { return false; }
var newLogin = new SimApiLoginItem(login.Id, login.Type, login.Meta);
cache.SetString(token,JsonSerializer.Serialize(newLogin));
return true;
cache.SetString(token, JsonSerializer.Serialize(loginItem));
return token;
}
/// <summary>
@@ -65,7 +43,7 @@ public class SimApiAuth(IDistributedCache cache)
public SimApiLoginItem? GetLogin(string token)
{
var login = cache.GetString(token);
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : default;
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : null;
}
/// <summary>
+32
View File
@@ -0,0 +1,32 @@
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
namespace SimApi.Helpers;
public class SimApiCache(IDistributedCache cache)
{
private const string Prefix = "SimApi:Cache:";
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
{
if (options is not null)
{
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
}
else
{
cache.SetString(Prefix + key, SimApiUtil.Json(value));
}
}
public string? Get(string key)
{
return cache.GetString(Prefix + key);
}
public T? Get<T>(string key)
{
var data = cache.GetString(Prefix + key);
return data == null ? default : JsonSerializer.Deserialize<T>(data);
}
}
+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;
}
}
+33
View File
@@ -0,0 +1,33 @@
using System;
using System.Linq;
using System.Text;
using Hangfire.Dashboard;
using Microsoft.AspNetCore.Http;
namespace SimApi.Helpers;
public class SimApiJobWebAuth(string user, string pass) : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
var authHeader = httpContext.Request.Headers.Authorization.FirstOrDefault();
if (authHeader != null && authHeader.StartsWith("Basic "))
{
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
var username = decodedUsernamePassword.Split(':', 2)[0];
var password = decodedUsernamePassword.Split(':', 2)[1];
if (username == user && password == pass)
{
return true;
}
}
httpContext.Response.StatusCode = 401;
httpContext.Response.Headers.WWWAuthenticate = "Basic realm=\"SimApiBasicAuth\"";
httpContext.Response.WriteAsync("").Wait();
return false;
}
}
+34
View File
@@ -0,0 +1,34 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SimApi.Attributes;
using SimApi.Communications;
namespace SimApi.Helpers;
public class SimApiResponseFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
if (context.ActionDescriptor.EndpointMetadata.Any(meta => meta is OriginResponseAttribute))
{
return;
}
context.Result = context.Result switch
{
// 检查结果是否为 null
null => new OkObjectResult(new SimApiBaseResponse()),
ObjectResult { Value: SimApiBaseResponse simApiBaseResponse } =>
new OkObjectResult(simApiBaseResponse),
ObjectResult objectResult => new OkObjectResult(new SimApiBaseResponse<object>(objectResult.Value!)),
EmptyResult => new OkObjectResult(new SimApiBaseResponse()),
_ => context.Result
};
}
public void OnResultExecuted(ResultExecutedContext context)
{
}
}
+27 -6
View File
@@ -26,10 +26,10 @@ public class SimApiStorage
{
var options = apiOptions.SimApiStorageOptions;
HttpContextAccessor = httpContextAccessor;
Endpoint = options.Endpoint;
Endpoint = options.Endpoint!;
var useSsl = false;
string endpoint;
if (options.Endpoint.StartsWith("http://"))
if (options.Endpoint!.StartsWith("http://"))
{
endpoint = options.Endpoint.Replace("http://", string.Empty);
}
@@ -43,9 +43,9 @@ public class SimApiStorage
throw new Exception("SimApiStorage: Error Endpoint");
}
ServeUrl = options.ServeUrl;
ServeUrl = options.ServeUrl!;
if (ServeUrl.EndsWith('/')) throw new Exception("SimApiStorage: ServeUrl must not end with /");
Bucket = options.Bucket;
Bucket = options.Bucket!;
var mcb = new MinioClient().WithEndpoint(endpoint)
.WithCredentials(options.AccessKey, options.SecretKey);
if (useSsl)
@@ -112,7 +112,7 @@ public class SimApiStorage
/// <param name="path"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public string FullUrl(string path)
public string? FullUrl(string? path)
{
if (string.IsNullOrEmpty(path)) return path;
if(path.StartsWith("http://") || path.StartsWith("https://")) return path;
@@ -127,6 +127,27 @@ public class SimApiStorage
return path.StartsWith('~') ? string.Concat(url, path.AsSpan(1, path.Length - 1)) : $"{ServeUrl}{path}";
}
/// <summary>
/// 获取一个Path得访问URL
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string? GetUrl(string? path)
{
if (string.IsNullOrEmpty(path)) return path;
if (path.StartsWith("~/"))
{
var httpRequest = HttpContextAccessor.HttpContext?.Request;
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
return string.Concat(url, path.AsSpan(1, path.Length - 1));
}
if (path.StartsWith('/'))
{
return $"{ServeUrl}{path}";
}
return path;
}
/// <summary>
/// 从URL中获取相对路径 (如果url不是当前服务器的url,则原样返回)
/// </summary>
@@ -134,7 +155,7 @@ public class SimApiStorage
/// <returns></returns>
public string? GetPath(string? url)
{
return url?.Replace($"{Endpoint}/{Bucket}", string.Empty);
return url?.Replace($"{Endpoint}/{Bucket}", string.Empty).Replace(ServeUrl,string.Empty);
}
private void CheckPath(string path)
+84 -2
View File
@@ -1,5 +1,7 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
@@ -7,6 +9,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Text.Unicode;
using System.Xml.Serialization;
namespace SimApi.Helpers;
@@ -22,11 +25,59 @@ public static class SimApiUtil
/// </summary>
public static JsonSerializerOptions JsonOption => new()
{
// ReferenceHandler = ReferenceHandler.Preserve,
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
// DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public static string SimApiVersion
{
get
{
// 这里使用当前类(属于 NuGet 包)的程序集
var assembly = typeof(SimApiUtil).Assembly;
// 优先获取 AssemblyInformationalVersion(通常对应 NuGet 包版本,可能包含预发布标签)
var informationalVersion =
assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
if (!string.IsNullOrEmpty(informationalVersion))
{
return informationalVersion;
}
// 若不存在,则获取 AssemblyVersion(编译时版本)
var version = assembly.GetName().Version?.ToString();
return version ?? "Unknown";
}
}
public static string AppVersion
{
get
{
// 获取外层应用的入口程序集(通常是启动项目的程序集)
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly == null)
{
// 特殊场景(如单元测试、某些宿主环境)下,入口程序集可能为 null,可尝试获取调用栈中的上层程序集
entryAssembly = Assembly.GetCallingAssembly(); // 或 Assembly.GetExecutingAssembly() 视场景调整
}
// 优先获取应用的 AssemblyInformationalVersion
var informationalVersion = entryAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion;
if (!string.IsNullOrEmpty(informationalVersion))
{
return informationalVersion;
}
// 若不存在,则获取 AssemblyVersion
var version = entryAssembly.GetName().Version?.ToString();
return version ?? "Unknown";
}
}
/// <summary>
/// 当前秒级时间戳
/// </summary>
@@ -62,12 +113,43 @@ public static class SimApiUtil
return stringBuilder.ToString();
}
/// <summary>
/// sha1加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="mode">加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位</param>
/// <returns></returns>
public static string Sha1(string source, string mode = "x2")
{
var hash = SHA1.HashData(Encoding.UTF8.GetBytes(source));
var sb = new StringBuilder(hash.Length * 2);
foreach (var b in hash)
{
sb.Append(b.ToString(mode));
}
return sb.ToString();
}
/// <summary>
/// 将XML字符串序列化为对象
/// </summary>
/// <param name="source"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T XmlDeserialize<T>(string source)
{
var xmlConvertor = new XmlSerializer(typeof(T));
using var reader = new StringReader(source);
return (T)xmlConvertor.Deserialize(reader)!;
}
/// <summary>
/// 将对象序列化成JSON (控制台输出中文不会被编码)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string Json(object obj)
public static string Json(object? obj)
{
return JsonSerializer.Serialize(obj, JsonOption);
}
+13 -5
View File
@@ -1,16 +1,14 @@
using System;
using Microsoft.Extensions.Logging;
using SimApi.Helpers;
namespace SimApi.Logger;
public class SimApiLogger(string name) : ILogger
{
public IDisposable BeginScope<TState>(TState state) => default!;
public IDisposable BeginScope<TState>(TState state) where TState : notnull => default!;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception, string> formatter)
{
Console.ForegroundColor = logLevel switch
@@ -23,12 +21,22 @@ public class SimApiLogger(string name) : ILogger
_ => ConsoleColor.White
};
var message =
$"[ {name} ][ {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")} ][ {logLevel.ToString()} ]\n{state}\n";
$"[ {name} ][ {DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} ][ {logLevel.ToString()} ]\n{state}\n";
if (exception != null)
{
message += $"{exception}\n";
}
Console.WriteLine(message);
Console.ResetColor();
}
}
public class EmptyDisposable : IDisposable
{
public static EmptyDisposable Instance { get; } = new EmptyDisposable();
public void Dispose()
{
}
}
-15
View File
@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace SimApi.Logger;
public class SimApiLoggerConfiguration
{
public int EventId { get; set; }
public Dictionary<LogLevel, ConsoleColor> LogLevels { get; set; } = new()
{
[LogLevel.Information] = ConsoleColor.Green
};
}
+5 -8
View File
@@ -14,21 +14,18 @@ public class SimApiAuthMiddleware(RequestDelegate next)
{
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
{
string token = null;
string? token = null;
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
{
token = header;
}
if (!string.IsNullOrEmpty(token))
if (string.IsNullOrEmpty(token)) return next(httpContext);
var login = auth.GetLogin(token);
if (login != null)
{
var login = auth.GetLogin(token);
if (login != null)
{
httpContext.Items.Add("LoginInfo", login);
}
httpContext.Items.Add("LoginInfo", login);
}
return next(httpContext);
}
}
+48 -33
View File
@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SimApi.Communications;
@@ -20,50 +19,66 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
context.Response.Headers["Query-Id"] = header;
}
SimApiBaseResponse response;
try
{
await next(context);
switch (context.Response.StatusCode)
if (!context.Response.HasStarted)
{
case 200:
break;
case 404:
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
case 301:
case 302:
break;
default:
throw new SimApiException(context.Response.StatusCode);
switch (context.Response.StatusCode)
{
case 200:
case 301:
case 302:
break;
case 404:
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
default:
throw new SimApiException(context.Response.StatusCode);
}
}
}
catch (SimApiException ex)
{
response = string.IsNullOrEmpty(ex.Message)
? new SimApiBaseResponse(ex.Code)
: new SimApiBaseResponse(ex.Code, ex.Message);
ErrorResponse(context, response);
}
catch (Exception ex)
{
log.LogError("{Msg}", ex.Message);
log.LogError("{Msg}", ex.StackTrace);
response = new SimApiBaseResponse(500, ex.Message);
ErrorResponse(context, response);
// 解包异步异常
ex = UnwrapAggregateException(ex);
SimApiBaseResponse response;
if (ex is SimApiException simEx)
{
response = string.IsNullOrEmpty(simEx.Message)
? new SimApiBaseResponse(simEx.Code)
: new SimApiBaseResponse(simEx.Code, simEx.Message);
}
else
{
log.LogError(ex, "服务器异常");
response = new SimApiBaseResponse(500, "服务器错误");
}
await ErrorResponseAsync(context, response);
}
}
/// <summary>
/// 异常抛出错误
/// </summary>
/// <param name="context"></param>
/// <param name="response"></param>
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
private static Exception UnwrapAggregateException(Exception ex)
{
if (context.Response.HasStarted) return;
while (ex is AggregateException aggEx && aggEx.InnerException != null)
{
ex = aggEx.InnerException;
}
return ex;
}
/// <summary>
/// 异步输出错误响应(修复异步异常捕获核心)
/// </summary>
private static async Task ErrorResponseAsync(HttpContext context, SimApiBaseResponse response)
{
// 响应已开始则直接返回,不修改
if (context.Response.HasStarted)
return;
context.Response.StatusCode = 200;
context.Response.Headers.Append("Content-Type", "application/json");
context.Response.WriteAsync(response.ToString());
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(response.ToString());
}
}
+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);
}
+2 -2
View File
@@ -20,7 +20,7 @@ public class SimApiBaseModel
public void MapData<TS>(TS source, bool mapAll = false)
{
//获取要赋值的源数据不为null的项目
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
var sourceProps = source!.GetType().GetProperties().Where(x => x.GetValue(source) != null)
.Select(x => new
{
x.Name,
@@ -49,7 +49,7 @@ public class SimApiBaseModel
public void MapData<TS>(TS source, string[] mapFields)
{
//获取要赋值的源数据不为null的项目
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
var sourceProps = source!.GetType().GetProperties().Where(x => x.GetValue(source) != null)
.Select(x => new
{
x.Name,
+1056 -41
View File
File diff suppressed because it is too large Load Diff
+12 -30
View File
@@ -1,42 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Library</OutputType>
<PackOnBuild>true</PackOnBuild>
<Version>0.2.3</Version>
<IsPackable>true</IsPackable>
<Version>0.0.0</Version>
<Authors>xRain@SimcuTeam</Authors>
<Description>AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库</Description>
<PackageId>Simcu.SimApi</PackageId>
<IsPackable>true</IsPackable>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<IncludeSymbols>true</IncludeSymbols>
<ReleaseVersion>5.0.0</ReleaseVersion>
<SynchReleaseVersion>false</SynchReleaseVersion>
<Nullable>enable</Nullable>
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageVersion>5.0.2</PackageVersion>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="Helpers\"/>
<Folder Include="Communications\"/>
<Folder Include="Controllers\"/>
<Folder Include="Middlewares\"/>
<Folder Include="Exceptions\"/>
<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="10.0.1" />
<PackageReference Include="Minio" Version="7.0.0" />
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/>
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Minio" Version="6.0.3" />
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical"/>
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
</Project>
+298 -67
View File
@@ -1,13 +1,26 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using Hangfire;
using Hangfire.Console;
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;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SimApi.Attributes;
using SimApi.CoceSdk;
using SimApi.Configurations;
using SimApi.Logger;
using SimApi.SwaggerFilters;
namespace SimApi;
@@ -18,10 +31,16 @@ public static class SimApiExtensions
{
//**********快捷添加**************
public static IServiceCollection AddSimApi(this IServiceCollection builder,
Action<SimApiOptions> options = null)
Action<SimApiOptions>? options = null)
{
var simApiOptions = new SimApiOptions();
options?.Invoke(simApiOptions);
if (simApiOptions.RedisConfiguration != null)
{
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
builder.AddSingleton<SimApiCache>();
}
if (simApiOptions.EnableLogger)
{
builder.AddLogging(logger =>
@@ -37,6 +56,35 @@ public static class SimApiExtensions
builder.AddSingleton<SimApiAuth>();
}
if (simApiOptions.EnableCoceSdk)
{
builder.AddSingleton<CoceApp>();
}
if (simApiOptions.EnableJob)
{
builder.AddHangfire(x =>
{
var redisOption = new RedisStorageOptions();
if (simApiOptions.SimApiJobOptions.Database.HasValue)
{
redisOption.Db = simApiOptions.SimApiJobOptions.Database.Value;
}
x.UseRedisStorage(simApiOptions.SimApiJobOptions.RedisConfiguration ??
simApiOptions.RedisConfiguration, redisOption);
x.UseConsole();
});
foreach (var server in simApiOptions.SimApiJobOptions.Servers)
{
builder.AddHangfireServer(hfs =>
{
hfs.Queues = server.Queues;
hfs.WorkerCount = server.WorkerNum;
});
}
}
if (simApiOptions.EnableCors)
{
builder.AddCors(cors => cors.AddPolicy("any",
@@ -46,6 +94,19 @@ public static class SimApiExtensions
if (simApiOptions.EnableSynapse)
{
builder.AddSingleton<Synapse>();
//自动依赖注入
var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var assembly = callingMethod?.DeclaringType?.Assembly;
var types = assembly?.GetTypes() ?? [];
foreach (var type in types)
{
var methodsWithSynapse = type.GetMethods()
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
m.GetCustomAttribute<SynapseEventAttribute>() != null);
if (!methodsWithSynapse.Any()) continue;
builder.AddScoped(type);
}
}
// 使用SimApiDoc
@@ -63,30 +124,116 @@ public static class SimApiExtensions
});
}
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>();
}
x.DocInclusionPredicate((docName, apiDesc) =>
{
// 获取接口标记的 GroupName(未标记则为 null
var actionGroupName = apiDesc.ActionDescriptor.EndpointMetadata
.OfType<ApiExplorerSettingsAttribute>()
.FirstOrDefault()?.GroupName;
// 情况1:接口未标记任何 GroupNameactionGroupName 为 null
if (actionGroupName == null)
{
return docName == "api"; // 未分组接口只属于默认分组v1
}
return docName == actionGroupName;
});
x.EnableAnnotations();
var haveOauth = false;
var haveSimApiAuth = false;
var oauthFlows = new OpenApiOAuthFlows();
foreach (var auth in docOptions.ApiAuth.Type)
{
switch (auth)
{
case "SimApiAuth":
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
x.AddSecurityDefinition("SimApiAuth",
new OpenApiSecurityScheme
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "HeaderToken"
}
},
new[] { "readAccess", "writeAccess" }
}
});
haveSimApiAuth = true;
Name = "Token",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
break;
case "ClientCredentials":
oauthFlows.ClientCredentials = new OpenApiOAuthFlow
@@ -135,30 +282,6 @@ public static class SimApiExtensions
Description = docOptions.ApiAuth.Description,
In = ParameterLocation.Header
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
}
},
new[] { "SimApiAuth" }
}
});
}
if (haveSimApiAuth)
{
x.AddSecurityDefinition("HeaderToken",
new OpenApiSecurityScheme
{
Name = "Token",
In = ParameterLocation.Header
});
}
});
}
@@ -185,22 +308,72 @@ public static class SimApiExtensions
builder.AddSingleton<SimApiStorage>();
}
if (simApiOptions.EnableSimApiResponseFilter)
{
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
.AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
}
builder.AddSingleton(simApiOptions);
return builder;
}
public static IHost UseSimApi(this IHost builder)
{
var options = builder.Services.GetRequiredService<SimApiOptions>();
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
logger.LogInformation("主应用版本: {AppVersion}\nSimApi版本: {SimApiVersion}", SimApiUtil.AppVersion,
SimApiUtil.SimApiVersion);
if (options.RedisConfiguration != null)
{
logger.LogInformation("开始配置 RedisCache ...");
}
//请求一下检测存储错误
if (options.EnableSimApiStorage)
{
logger.LogInformation("开始配置SimApiStorage...");
builder.Services.GetService<SimApiStorage>();
}
if (options.EnableCoceSdk)
{
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
options.CoceSdkOptions.AppId);
}
if (options.EnableSynapse)
{
var synapse = builder.Services.GetRequiredService<Synapse>();
synapse.Init();
}
if (options.EnableJob)
{
logger.LogInformation("开始配置 SimApiJob ...");
}
return builder;
}
/// <summary>
/// 使用所有SimApi自定义中间件
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseSimApi(this IApplicationBuilder builder)
public static WebApplication UseSimApi(this WebApplication builder)
{
var options = builder.ApplicationServices.GetRequiredService<SimApiOptions>();
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
var options = builder.Services.GetRequiredService<SimApiOptions>();
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
UseSimApi((IHost)builder);
if (options.EnableForwardHeaders)
{
logger.LogInformation("开始配置ForwardedHeaders...");
@@ -213,28 +386,86 @@ public static class SimApiExtensions
builder.UseCors("any");
}
if (options.EnableSimApiResponseFilter)
{
logger.LogInformation("开始配置SimApiResponseFilter...");
builder.MapControllers();
}
if (options.EnableSimApiAuth)
{
logger.LogInformation("开始配置SimApiAuth...");
builder.UseMiddleware<SimApiAuthMiddleware>();
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
defaults: new
{
controller = "SimApiAuth",
action = "UserInfo"
});
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
defaults: new
{
controller = "SimApiAuth",
action = "CheckLogin"
});
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
defaults: new
{
controller = "SimApiAuth",
action = "Logout"
});
if (options.EnableCoceSdk)
{
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
options.CoceSdkOptions.AppId);
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/login",
defaults: new
{
controller = "Coce",
action = "Login"
});
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups",
defaults: new
{
controller = "Coce",
action = "ListGroups"
});
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config",
defaults: new
{
controller = "Coce",
action = "GetConfig"
});
}
}
if (options.EnableVersionUrl)
{
builder.MapControllerRoute(name: "Versions", pattern: "/versions",
defaults: new
{
controller = "SimApiCommon",
action = "Versions"
});
}
if (options.EnableSimApiDoc)
{
logger.LogInformation("开始配置SimApiDoc...");
var docOptions = options.SimApiDocOptions;
builder.UseSwagger(x => x.RouteTemplate = "/swagger/{documentName}.json").UseSwaggerUI(x =>
{
x.DocumentTitle = docOptions.DocumentTitle;
foreach (var group in docOptions.ApiGroups)
builder.UseSwagger(x => x.RouteTemplate = "/swagger/{documentName}.json")
.UseSwaggerUI(x =>
{
x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name);
}
x.DocumentTitle = docOptions.DocumentTitle;
foreach (var group in docOptions.ApiGroups)
{
x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name);
}
x.EnableValidator();
x.SupportedSubmitMethods(docOptions.SupportedMethod);
x.DisplayRequestDuration();
});
x.SupportedSubmitMethods(docOptions.SupportedMethod);
x.DisplayRequestDuration();
});
}
if (options.EnableSimApiException)
@@ -243,22 +474,22 @@ public static class SimApiExtensions
builder.UseMiddleware<SimApiExceptionMiddleware>();
}
//请求一下检测存储错误
if (options.EnableSimApiStorage)
{
logger.LogInformation("开始配置SimApiStorage...");
builder.ApplicationServices.GetService<SimApiStorage>();
}
if (options.EnableLowerUrl)
{
logger.LogInformation("开始配置使用URL小写...");
}
if (options.EnableSynapse)
if (options is { EnableJob: true, SimApiJobOptions.DashboardUrl: not null })
{
var synapse = builder.ApplicationServices.GetRequiredService<Synapse>();
synapse.Init();
logger.LogInformation("开始配置 SimApiJob Web控制台...");
builder.UseHangfireDashboard(options.SimApiJobOptions.DashboardUrl, new DashboardOptions
{
Authorization =
[
new SimApiJobWebAuth(options.SimApiJobOptions.DashboardAuthUser,
options.SimApiJobOptions.DashboardAuthPass)
]
});
}
return builder;
+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), [] }
});
}
}
}
@@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
namespace SimApi.SwaggerFilters;
public class SimApiResponseOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// 1. 跳过标记了 [OriginResponseAttribute] 的接口(不包装)
if (context.MethodInfo.DeclaringType?.GetCustomAttributes<OriginResponseAttribute>(true).Any() == true
|| context.MethodInfo.GetCustomAttributes<OriginResponseAttribute>(true).Any())
{
return;
}
// 2. 获取控制器方法声明的“原始返回类型”(如 Task<UserDto> → UserDto
var returnType = GetUnwrappedReturnType(context.MethodInfo.ReturnType, context);
if (IsAlreadyWrappedType(returnType))
{
return; // 保留原始返回类型的文档描述
}
// 3. 定义包装后的目标类型(泛型/非泛型)
Type wrappedType;
if (returnType == typeof(void) || returnType == typeof(EmptyResult))
{
// 无数据:用非泛型 SimApiBaseResponse
wrappedType = typeof(SimApiBaseResponse);
}
else
{
// 有数据:用泛型 SimApiBaseResponse<T>T 为原始返回类型)
wrappedType = typeof(SimApiBaseResponse<>).MakeGenericType(returnType);
}
// 4. 让 Swagger 生成包装类型的 Schema
var schema = context.SchemaGenerator.GenerateSchema(wrappedType, context.SchemaRepository);
// 5. 替换 Swagger 文档中的响应类型(只保留 200 OK 的响应,匹配过滤器逻辑)
operation.Responses.Clear(); // 清除默认响应(如 200 返回原始类型)
operation.Responses.Add("200", new OpenApiResponse
{
Description = "请求成功",
Content = new Dictionary<string, OpenApiMediaType>
{
{
"application/json", // 只保留 JSON 格式(配合之前的全局配置)
new OpenApiMediaType
{
Schema = schema
}
}
}
});
}
private static Type GetUnwrappedReturnType(Type returnType, OperationFilterContext context)
{
// 处理 Task<T>(异步方法)
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
{
returnType = returnType.GetGenericArguments()[0];
}
// 处理 IActionResult/ObjectResult(如 return Ok(userDto)
if (!typeof(IActionResult).IsAssignableFrom(returnType)) return returnType;
// 从方法返回语句中提取原始类型(需结合特性,或默认用 object)
// 更精准的方式:让控制器方法用 [ProducesResponseType(typeof(UserDto), 200)] 声明原始类型
var producesAttr = context.MethodInfo.GetCustomAttributes<ProducesResponseTypeAttribute>()
.FirstOrDefault(a => a.StatusCode == 200);
if (producesAttr?.Type != null && producesAttr.Type != typeof(void))
{
return producesAttr.Type;
}
return typeof(object); // 无法识别时默认用 object
}
// 辅助方法:判断类型是否已经是 SimApiBaseResponse 及其泛型
private static bool IsAlreadyWrappedType(Type type)
{
// 情况1:类型本身是 SimApiBaseResponse 或其泛型
if (type == typeof(SimApiBaseResponse) ||
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(SimApiBaseResponse<>)))
{
return true;
}
// 情况2:类型是 SimApiBaseResponse 的子类(非泛型)
if (type.IsSubclassOf(typeof(SimApiBaseResponse)))
{
return true;
}
// 情况3:类型是 SimApiBaseResponse<T> 的子类(泛型)
// 检查是否继承自泛型父类 SimApiBaseResponse<>(任意 T
if (type.BaseType is { IsGenericType: true })
{
var genericBaseType = type.BaseType.GetGenericTypeDefinition();
if (genericBaseType == typeof(SimApiBaseResponse<>))
{
return true;
}
}
// 其他情况:不是包装类型或其子类
return false;
}
}
+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 // 签名相关参数通常为字符串类型
}
});
}
}
}
+63
View File
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Protocol;
namespace SimApi;
public partial class Synapse
{
public event EventHandler<ConfigStoreItem>? OnConfigChanged;
private Dictionary<string, string> CurrentConfig { get; } = new();
private string ConfigStoreTopicPrefix => $"{Options.SysName}/synapse-config-store/";
private bool FireSetConfig(string key, string value)
{
if (key.Contains('#') || key.Contains('+')) return false;
var topic = $"{Options.SysName}/synapse-config-store/{key}";
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(value)
.WithRetainFlag()
.Build();
if (!Client!.IsConnected) return false;
Client!.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug("Synapse Config Set: {Config} => {Data}", key, value);
return true;
}
private string? FireGetConfig(string key)
{
return CurrentConfig.GetValueOrDefault(key);
}
private void RunConfigStoreServer()
{
Client!.ApplicationMessageReceivedAsync += e =>
{
if (!e.ApplicationMessage.Topic.StartsWith(ConfigStoreTopicPrefix)) return Task.CompletedTask;
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
var eventName = e.ApplicationMessage.Topic.Replace(ConfigStoreTopicPrefix, string.Empty);
CurrentConfig[eventName] = reqBody;
OnConfigChanged?.Invoke(this, new ConfigStoreItem(eventName, reqBody));
logger.LogDebug("Synapse Config Changed: {Config} => {Data}", eventName, reqBody);
return Task.CompletedTask;
};
SubConfigStoreServerTopic();
}
private void SubConfigStoreServerTopic()
{
var csSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(o =>
o.WithTopic($"{ConfigStoreTopicPrefix}#").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
.Build();
Client!.SubscribeAsync(csSubOpts).Wait();
}
public record ConfigStoreItem(string Key, string Value);
}
+22 -20
View File
@@ -1,31 +1,33 @@
using System;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading;
using Microsoft.Extensions.Logging;
using MQTTnet;
using SimApi.Helpers;
namespace SimApi;
public partial class Synapse
{
private void RunEventClient()
private bool FireEvent(string eventName, object? param)
{
EventClientChannel = CreateChannel(0, "EventClient");
}
private void FireEvent(string eventName, object param)
{
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
var router = $"event.{Options.AppName}.{eventName}";
var props = EventClientChannel.CreateBasicProperties();
props.AppId = Options.AppId;
props.MessageId = Guid.NewGuid().ToString();
props.ReplyTo = Options.AppName;
props.Type = eventName;
EventClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson));
Logger.LogDebug("Event Publish: {OptionsAppName}.{EventName}\n{ParamJson}", Options.AppName, eventName,
paramJson);
string paramJson;
if (param is string strParam)
{
paramJson = strParam;
}
else
{
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
}
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(paramJson)
.WithRetainFlag(false)
.Build();
if (!Client!.IsConnected) return false;
Client.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug("Synapse Event Publish: {Event}@{App} {Json}", eventName, Options.AppName, paramJson);
return true;
}
}
+60 -32
View File
@@ -1,50 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;
using MQTTnet;
using SimApi.Helpers;
namespace SimApi;
public partial class Synapse
{
private string EventServerTopicPrefix => $"{Options.SysName}/event/";
private void RunEventServer()
{
EventServerChannel = CreateChannel(Options.EventProcessorNum, "EventServer");
var queue = $"{Options.SysName}_{Options.AppName}_event";
EventServerChannel.QueueDeclare(queue, true, false, true, null);
foreach (var ev in EventRegistry.Where(ev => !ev.Key.Contains('*') && !ev.Key.Contains('#')))
Client!.ApplicationMessageReceivedAsync += async e =>
{
EventServerChannel.QueueBind(queue, Options.SysName, $"event.{ev.Key}", null);
}
var consumer = new EventingBasicConsumer(EventServerChannel);
consumer.Received += (ch, ea) =>
{
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
Logger.LogDebug("Event Receive: {BasicPropertiesReplyTo}.{BasicPropertiesType}\n{S}",
ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, reqBody);
var key = ea.RoutingKey.Replace("event.", string.Empty);
var method = EventRegistry.FirstOrDefault(x => x.Key == key);
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
var mt = callClass.GetType().GetMethod(method.Method);
var pt = mt.GetParameters()[0].ParameterType;
try
await Task.Run(async () =>
{
mt.Invoke(callClass, pt == typeof(string)
? new object[] { reqBody }
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
EventServerChannel.BasicAck(ea.DeliveryTag, false);
}
catch (Exception e)
{
Logger.LogError("Event Processor Error: {Err}", e.InnerException);
EventServerChannel.BasicNack(ea.DeliveryTag, false, false);
}
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return;
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
var eventName = e.ApplicationMessage.Topic.Replace(EventServerTopicPrefix, string.Empty);
logger.LogDebug("Synapse Event Receive: {EventName}\n{Body}", eventName, reqBody);
var methods = EventRegistry
.Where(x => Regex.IsMatch(eventName,
"^" + Regex.Escape(x.Key!).Replace("\\+", "[^/]+").Replace("\\#", ".*") + "$"))
.ToArray();
var tasks = methods.Select(method => Task.Run(() =>
{
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
var mt = callClass.GetType().GetMethod(method.Method!);
try
{
if (mt!.GetParameters().Length == 2)
{
var pt = mt.GetParameters()[1].ParameterType;
mt.Invoke(callClass, pt == typeof(string)
? [eventName, reqBody]
: [eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption)]);
}
else
{
mt.Invoke(callClass, new object[] { eventName });
}
}
catch (Exception ex)
{
logger.LogError("Synapse Event Processor Error: {Err}\n{Stack}", ex.Message, ex.StackTrace);
}
}))
.ToList();
await Task.WhenAll(tasks);
});
};
EventServerChannel.BasicConsume(queue, false, "", false, false, null, consumer);
SubEventServerTopic();
}
private void SubEventServerTopic()
{
foreach (var ev in EventRegistry)
{
var topic = $"{EventServerTopicPrefix}{ev.Key}";
if (Options.EventLoadBalancing)
{
topic = "$queue/" + topic;
}
var evSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(o => o.WithTopic(topic)).Build();
Client!.SubscribeAsync(evSubOpts).Wait();
logger.LogDebug("Synapse Event Register Event Success: {EventName}\nFull Topic: {Topic}", ev.Key, topic);
}
}
}
+75 -40
View File
@@ -1,67 +1,102 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;
using MQTTnet;
using SimApi.Communications;
using SimApi.Helpers;
using System.Collections.Concurrent;
namespace SimApi;
public partial class Synapse
{
private Dictionary<string, byte[]> ResponseCache { get; } = new();
private ConcurrentDictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
private string EventClientTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
private void RunRpcClient()
{
RpcClientChannel = CreateChannel(0, "RpcClient");
var queue = $"{Options.SysName}_{Options.AppName}_client_{Options.AppId}";
var router = $"client.{Options.AppName}.{Options.AppId}";
RpcClientChannel.QueueDeclare(queue, true, false, true, null);
RpcClientChannel.QueueBind(queue, Options.SysName, router, null);
var consumer = new EventingBasicConsumer(RpcClientChannel);
consumer.Received += (ch, ea) =>
Client!.ApplicationMessageReceivedAsync += e =>
{
ResponseCache.Add(ea.BasicProperties.CorrelationId, ea.Body.ToArray());
RpcClientChannel.BasicAck(ea.DeliveryTag, false);
Logger.LogDebug(
"RPC Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
ea.BasicProperties.CorrelationId, ea.BasicProperties.Type, ea.BasicProperties.ReplyTo, Options.AppName,
Encoding.UTF8.GetString(ea.Body.ToArray()));
if (!e.ApplicationMessage.Topic.StartsWith(EventClientTopicPrefix)) return Task.CompletedTask;
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
var messageId = e.ApplicationMessage.Topic.Replace(EventClientTopicPrefix, string.Empty);
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
tcs.SetResult(reqBody);
ResponseCompletionSources.Remove(messageId, out _);
return Task.CompletedTask;
};
RpcClientChannel.BasicConsume(queue, false, "", false, false, null, consumer);
SubRpcClientTopic();
}
private string FireRpc(string app, string action, object param)
private void SubRpcClientTopic()
{
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
var router = $"server.{app}";
string response;
var props = RpcClientChannel.CreateBasicProperties();
props.AppId = Options.AppId;
props.MessageId = Guid.NewGuid().ToString();
props.Type = action;
props.ReplyTo = Options.AppName;
RpcClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson));
Logger.LogDebug("RPC Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}",
props.MessageId,
Options.AppName, action, app, paramJson);
var ts = SimApiUtil.TimestampNow;
while (true)
var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(o => o.WithTopic($"{EventClientTopicPrefix}+")).Build();
Client!.SubscribeAsync(rcSubOpts).Wait();
}
private string? FireRpc(string app, string action, object? param, Dictionary<string, string>? headers = null,
int? timeout = null)
{
// 移除锁语句
string paramJson;
if (param is string strParam)
{
if (SimApiUtil.TimestampNow - ts > Options.RpcTimeout)
paramJson = strParam;
}
else
{
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
}
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
var messageId = Guid.NewGuid().ToString();
var tcs = new TaskCompletionSource<string>();
ResponseCompletionSources.TryAdd(messageId, tcs);
var messageBuilder = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(paramJson)
.WithResponseTopic($"{Options.AppName},{Options.AppId},{messageId}")
.WithContentType("application/json")
.WithRetainFlag(false);
foreach (var h in headers ?? new Dictionary<string, string>())
{
messageBuilder.WithUserProperty(h.Key, h.Value);
}
var message = messageBuilder.Build();
if (!Client!.IsConnected) return null;
Client.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug(
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
string response;
try
{
timeout ??= Options.RpcTimeout;
if (tcs.Task.Wait(timeout.Value * 1000))
{
response = tcs.Task.Result;
logger.LogDebug(
"Synapse RPC Client Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
messageId, action, app, Options.AppName, response);
}
else
{
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
break;
}
if (ResponseCache.TryGetValue(props.MessageId, out var value))
{
response = Encoding.UTF8.GetString(value);
ResponseCache.Remove(props.MessageId);
break;
}
}
catch
{
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"),
SimApiUtil.JsonOption);
}
return response;
}
}
+95 -64
View File
@@ -1,10 +1,12 @@
using System;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;
using MQTTnet;
using MQTTnet.Protocol;
using SimApi.Communications;
using SimApi.Exceptions;
using SimApi.Helpers;
@@ -14,80 +16,109 @@ namespace SimApi;
public partial class Synapse
{
private string RpcServerTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/server/";
private void RunRpcServer()
{
RpcServerChannel = CreateChannel(Options.RpcProcessorNum, "RpcServer");
var queue = $"{Options.SysName}_{Options.AppName}_server";
var router = $"server.{Options.AppName}";
RpcServerChannel.QueueDeclare(queue, true, false, true, null);
RpcServerChannel.QueueBind(queue, Options.SysName, router, null);
var consumer = new EventingBasicConsumer(RpcServerChannel);
consumer.Received += (ch, ea) =>
Client!.ApplicationMessageReceivedAsync += async e =>
{
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
Logger.LogDebug(
"RPC Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
ea.BasicProperties.MessageId, ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, Options.AppName,
reqBody);
var res = new SimApiBaseResponse(404, "method not found");
var method = RpcRegistry.FirstOrDefault(x => x.Key == ea.BasicProperties.Type);
if (method != null)
await Task.Run(() =>
{
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
var mt = callClass.GetType().GetMethod(method.Method);
var param = Array.Empty<object>();
try
if (!e.ApplicationMessage.Topic.StartsWith(RpcServerTopicPrefix)) return;
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
var action = e.ApplicationMessage.Topic.Replace(RpcServerTopicPrefix, string.Empty);
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
logger.LogDebug(
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
appInfo[2], appInfo[0], action, Options.AppName, reqBody);
SimApiBaseResponse res;
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
if (method == null)
{
var pt = mt.GetParameters()[0].ParameterType;
if (pt == typeof(string))
res = new SimApiBaseResponse(404, "method not found");
}
else
{
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
var mt = callClass.GetType().GetMethod(method.Method!);
try
{
param = new[] { reqBody };
}
else
{
var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption);
param = new[] { paramObj };
}
var methodParams = mt!.GetParameters();
object? ret;
switch (methodParams.Length)
{
case 1:
var pt = mt.GetParameters()[0].ParameterType;
var param = pt == typeof(string)
? [reqBody]
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
ret = mt.Invoke(callClass, param);
break;
case 2:
var headerData =
e.ApplicationMessage.UserProperties.ToDictionary(x => x.Name, x => x.Value);
var pt2 = mt.GetParameters()[0].ParameterType;
var param2 = pt2 == typeof(string)
? [reqBody]
: new[]
{
JsonSerializer.Deserialize(reqBody, pt2, SimApiUtil.JsonOption), headerData
};
ret = mt.Invoke(callClass, param2);
break;
default:
ret = mt.Invoke(callClass, []);
break;
}
var ret = mt.Invoke(callClass, param);
res = new SimApiBaseResponse<object>
{
Data = ret
};
}
catch (TargetInvocationException e)
{
if (e.InnerException is SimApiException ie)
{
Logger.LogDebug("RPC调用错误: {Err}", ie.Message);
res = new SimApiBaseResponse(ie.Code, ie.Message);
res = new SimApiBaseResponse<object?>
{
Data = ret
};
}
else
catch (TargetInvocationException ex)
{
res = new SimApiBaseResponse(500, e.Message);
if (ex.InnerException is SimApiException ie)
{
logger.LogDebug("Synapse RPC调用错误: {Err}", ie.Message);
res = new SimApiBaseResponse(ie.Code, ie.Message);
}
else
{
logger.LogError("Synapse RPC 方法异常: {Err}\n{Stack}", ex.Message, ex.StackTrace);
res = new SimApiBaseResponse(500, ex.Message);
}
}
catch (Exception ex)
{
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
res = new SimApiBaseResponse(500, ex.Message);
}
}
catch (Exception e)
{
Logger.LogDebug("RPC调用失败: {Err}", e.Message);
res = new SimApiBaseResponse(500, e.Message);
}
}
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
var reply = $"client.{ea.BasicProperties.ReplyTo}.{ea.BasicProperties.AppId}";
var props = RpcServerChannel.CreateBasicProperties();
props.AppId = Options.AppId;
props.CorrelationId = ea.BasicProperties.MessageId;
props.MessageId = Guid.NewGuid().ToString();
props.ReplyTo = Options.AppName;
props.Type = ea.BasicProperties.Type;
RpcServerChannel.BasicPublish(Options.SysName, reply, false, props, Encoding.UTF8.GetBytes(returnJson));
Logger.LogDebug(
"Rpc Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
ea.BasicProperties.MessageId, ea.BasicProperties.Type, Options.AppName, ea.BasicProperties.ReplyTo,
returnJson);
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
var message = new MqttApplicationMessageBuilder()
.WithTopic(reply)
.WithPayload(returnJson)
.WithRetainFlag(false)
.Build();
if (!Client.IsConnected) return;
Client.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug(
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
appInfo[2], action, Options.AppName, appInfo[0], returnJson);
});
};
RpcServerChannel.BasicConsume(queue, true, "", false, false, null, consumer);
SubRpcServerTopic();
}
private void SubRpcServerTopic()
{
var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(o =>
o.WithTopic($"$queue/{RpcServerTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
.Build();
Client!.SubscribeAsync(rsSubOpts).Wait();
}
}
+209 -132
View File
@@ -3,79 +3,63 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using MQTTnet;
using MQTTnet.Formatter;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Exceptions;
using SimApi.Helpers;
namespace SimApi;
public partial class Synapse
public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
{
private IServiceProvider Sp { get; }
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
private SimApiSynapseOptions Options { get; }
private MqttClientFactory MqttFactory { get; } = new();
public IMqttClient? Client { get; set; }
private ILogger<Synapse> Logger { get; }
private List<RegisterItem> EventRegistry { get; set; } = new();
private IConnection Connection { get; set; }
private IModel EventClientChannel { get; set; }
private IModel EventServerChannel { get; set; }
private IModel RpcClientChannel { get; set; }
private IModel RpcServerChannel { get; set; }
private List<RegisterItem> EventRegistry { get; set; }
private List<RegisterItem> RpcRegistry { get; set; }
public Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
{
Logger = logger;
Sp = sp;
Options = simApiOptions.SimApiSynapseOptions;
}
private List<RegisterItem> RpcRegistry { get; set; } = new();
public void Init()
{
ProcessAttribute();
Logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
{
Logger.LogCritical("Synapse初始化失败: AppName or SysName 错误");
logger.LogCritical("Synapse初始化失败: AppName SysName 不能为空");
}
Options.AppId ??= Guid.NewGuid().ToString();
Logger.LogInformation("System Name: {SysName}\nApp Name: {AppName}\nAppId: {AppId}", Options.SysName,
Options.AppName, Options.AppId);
logger.LogInformation("Synapse Sys Name: {SysName}\nSynapse App Name: {AppName}\nSynapse App Id: {AppId}",
Options.SysName, Options.AppName, Options.AppId);
CreateConnection();
CheckAndCreateExchange();
ProcessAttribute();
//事件客户端
if (Options.DisableEventClient)
{
Logger.LogWarning("Event Client Disabled: DisableEventClient set true");
logger.LogWarning("Synapse Event Client Disabled: DisableEventClient set true");
}
else
{
RunEventClient();
Logger.LogInformation("Event Client Ready");
logger.LogInformation("Synapse Event Client Ready");
}
//RPC客户端
if (Options.DisableRpcClient)
{
Logger.LogWarning("Rpc Client Disabled: DisableEventClient set true");
logger.LogWarning("Synapse Rpc Client Disabled: DisableEventClient set true");
}
else
{
RunRpcClient();
Logger.LogInformation("Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
logger.LogInformation("Synapse Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
}
if (RpcRegistry.Count > 0)
@@ -87,111 +71,159 @@ public partial class Synapse
{
RunEventServer();
}
if (Options.EnableConfigStore)
{
RunConfigStoreServer();
logger.LogInformation("Synapse Config Store Ready [{SysName}] ...", Options.SysName);
}
}
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param)
/// <summary>
/// 调用RPC使用明确的返回值类型
/// </summary>
/// <param name="appName"></param>
/// <param name="method"></param>
/// <param name="param"></param>
/// <param name="headers"></param>
/// <param name="timeout"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null,
Dictionary<string, string>? headers = null, int? timeout = null)
{
var res = new SimApiBaseResponse(500, "Rpc Client Disabled!");
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
if (Options.DisableRpcClient)
{
Logger.LogError("Rpc Client Disabled!");
logger.LogError("Synapse Rpc Client Disabled!");
}
else
{
var data = FireRpc(appName, method, param);
var data = FireRpc(appName, method, param, headers, timeout);
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
}
return res as SimApiBaseResponse<T>;
return (res as SimApiBaseResponse<T>)!;
}
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic param)
/// <summary>
/// 调用RPC使用object作为返回值类型
/// </summary>
/// <param name="appName"></param>
/// <param name="method"></param>
/// <param name="param"></param>
/// <param name="headers"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null,
Dictionary<string, string>? headers = null, int? timeout = null)
{
return Rpc<object>(appName, method, param);
return Rpc<object>(appName, method, param, headers, timeout);
}
public void Event(string eventName, dynamic param)
/// <summary>
/// 只能在Rpc方法中使用,快捷抛出异常返回
/// </summary>
/// <param name="code"></param>
/// <param name="message"></param>
/// <exception cref="SimApiException"></exception>
public void RpcError(int code, string message = "")
{
if (Options.DisableEventClient)
{
Logger.LogError("Event Client Disabled!");
}
else
{
FireEvent(eventName, param);
}
throw new SimApiException(code, message);
}
/// <summary>
/// 如果条件成立,则爆出错误
/// </summary>
/// <param name="condition"></param>
/// <param name="code"></param>
/// <param name="message"></param>
public void RpcErrorWhen(bool condition, int code, string message = "")
{
if (condition) RpcError(code, message);
}
/// <summary>
/// 发送一个事件x
/// </summary>
/// <param name="eventName"></param>
/// <param name="param"></param>
public bool Event(string eventName, dynamic? param = null)
{
if (!Options.DisableEventClient) return FireEvent(eventName, param);
logger.LogError("Synapse Event Client Disabled!");
return false;
}
/// <summary>
/// 设置一个系统配置项
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool SetConfig(string key, string value)
{
if (Options.EnableConfigStore) return FireSetConfig(key, value);
logger.LogError("Synapse Config Store Disabled!");
return false;
}
/// <summary>
/// 读取一个配置项,如果没有则为空
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string? GetConfig(string key)
{
if (Options.EnableConfigStore) return FireGetConfig(key);
logger.LogError("Synapse Config Store Disabled!");
return null;
}
private void CreateConnection()
{
var factory = new ConnectionFactory
Client = MqttFactory.CreateMqttClient();
var clientOpts = new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)
.WithWebSocketServer(o => o.WithUri(Options.Websocket))
.WithCredentials(Options.Username, Options.Password)
.WithClientId($"{Options.AppName}:{Options.AppId}")
.Build();
Client!.ConnectAsync(clientOpts, CancellationToken.None).Wait();
Client.ConnectedAsync += _ =>
{
HostName = Options.MqHost,
Port = Options.MqPort,
VirtualHost = Options.MqVHost,
UserName = Options.MqUser,
Password = Options.MqPass
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
//RPC客户端
if (!Options.DisableRpcClient) SubRpcClientTopic();
if (RpcRegistry.Count > 0) SubRpcServerTopic();
if (EventRegistry.Count > 0) SubEventServerTopic();
if (Options.EnableConfigStore) SubConfigStoreServerTopic();
return Task.CompletedTask;
};
try
//重连
Client.DisconnectedAsync += async _ =>
{
Connection = factory.CreateConnection();
Logger.LogInformation("连接RabbitMQ服务器成功");
}
catch (BrokerUnreachableException e)
{
Logger.LogError("连接RabbitMQ失败: \n{Err}", e);
}
}
private IModel CreateChannel(ushort processNum = 0, string desc = "unknow")
{
IModel channel = null;
try
{
var log = $"Channel [{desc}] 创建成功...";
channel = Connection.CreateModel();
if (processNum != 0)
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 断开连接,开始重连...", Options.AppName, Options.AppId);
await Task.Delay(TimeSpan.FromSeconds(5));
try
{
channel.BasicQos(0, processNum, false);
log += $"最大处理器数量: {processNum}";
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 开始连接MQTT服务器...", Options.AppName, Options.AppId);
Client.ConnectAsync(clientOpts).Wait();
}
Logger.LogInformation(log);
}
catch (ConnectFailureException e)
{
Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e);
}
return channel;
}
private void CheckAndCreateExchange()
{
var channel = CreateChannel(0, "Exchange");
try
{
channel.ExchangeDeclare(Options.SysName, ExchangeType.Topic, true, true, null);
Logger.LogDebug("Register Exchange Success");
}
catch (ConnectFailureException e)
{
Logger.LogError("Failed to declare Exchange.\n {Err}", e);
}
channel.Close();
Logger.LogDebug("Exchange Channel Closed");
catch
{
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 重连失败...", Options.AppName, Options.AppId);
}
};
}
private void ProcessAttribute()
{
EventRegistry = new List<RegisterItem>();
RpcRegistry = new List<RegisterItem>();
var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod();
var assembly = callingMethod.DeclaringType.Assembly;
var types = assembly.GetTypes(); // 获取程序集中的所有类型
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var assembly = callingMethod?.DeclaringType?.Assembly;
var types = assembly!.GetTypes(); // 获取程序集中的所有类型
foreach (var type in types)
{
var methods = type.GetMethods(); // 获取类型中的所有方法
@@ -200,48 +232,93 @@ public partial class Synapse
if (method.IsDefined(typeof(SynapseEventAttribute), false))
{
var attribute =
(SynapseEventAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseEventAttribute));
if (attribute != null)
(SynapseEventAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseEventAttribute))!;
var tmp = new RegisterItem
{
EventRegistry.Add(new RegisterItem
{
Key = attribute.Name ?? method.Name,
Class = type,
Method = method.Name
});
Key = attribute.Name ?? method.Name,
Class = type,
Method = method.Name
};
if (tmp.Key.StartsWith('/') || tmp.Key.EndsWith('/'))
{
logger.LogError("Synapse Event Register Error: {Key} Can't start or end of '/'", tmp.Key);
continue;
}
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
var mt = callClass.GetType().GetMethod(tmp.Method);
if (mt!.GetParameters().Length > 2 || mt.GetParameters().Length < 1)
{
logger.LogError(
"Synapse Event Register Error: Only one or two parameter supported. {Key} -> {Method}@{Class}",
tmp.Key, tmp.Method, tmp.Class.Name);
continue;
}
EventRegistry.Add(tmp);
}
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
{
var attribute =
(SynapseRpcAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseRpcAttribute));
if (attribute != null)
(SynapseRpcAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseRpcAttribute))!;
var tmp = new RegisterItem
{
RpcRegistry.Add(new RegisterItem
{
Key = attribute.Name ?? $"{type.Name}.{method.Name}",
Class = type,
Method = method.Name
});
Key = attribute.Name ?? $"{type.Name}.{method.Name}",
Class = type,
Method = method.Name
};
if (tmp.Key.Contains('/') || tmp.Key.Contains('#') || tmp.Key.Contains('+'))
{
logger.LogError("Synapse Rpc Register Error: {Key} contains '/' , '#' , '+'", tmp.Key);
continue;
}
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
var mt = callClass.GetType().GetMethod(tmp.Method);
if (mt!.GetParameters().Length > 2)
{
logger.LogError(
"Synapse Rpc Register Error: Only 1,2 or none parameter supported. {Key} -> {Method}@{Class}",
tmp.Key, tmp.Method, tmp.Class.Name);
continue;
}
if (mt.GetParameters().Length == 2 &&
mt.GetParameters()[1].ParameterType != typeof(Dictionary<string, string>))
{
logger.LogError(
"Synapse Rpc Register Error: RpcMethod Parameter 2 must be Dictionary<string, string>. {Key} -> {Method}@{Class}",
tmp.Key, tmp.Method, tmp.Class.Name);
continue;
}
if (RpcRegistry.Any(x => x.Key == tmp.Key))
{
logger.LogError("Synapse Rpc Register Error: {Key} Already Exists -> {Method}@{Class}", tmp.Key,
tmp.Method, tmp.Class.Name);
continue;
}
RpcRegistry.Add(tmp);
}
}
}
var events = EventRegistry.Aggregate(string.Empty,
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class!.Name}");
var rpcList = RpcRegistry.Aggregate(string.Empty,
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
Logger.LogInformation(">>> Synapse System 读取Event方法:{Event}\n>>>Synapse System 读取RPC方法:{Rpc}", events, rpcList);
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class!.Name}");
if (EventRegistry.Count > 0) logger.LogInformation(" >> Synapse System 读取Event方法:{Event}", events);
if (RpcRegistry.Count > 0) logger.LogInformation(" >> Synapse System 读取RPC方法:{Rpc}", rpcList);
}
}
public class RegisterItem
{
public string Key { get; set; }
public string? Key { get; init; }
public Type Class { get; set; }
public Type? Class { get; init; }
public string Method { get; set; }
public string? Method { get; init; }
}
+828
View File
@@ -0,0 +1,828 @@
# C# .NET Web API 编码规范(SimApi 框架版)
> **适用范围**:所有基于 `Simcu.SimApi` 框架的 .NET Web API 项目,适用于任何 AI 辅助编程工具(Claude、ChatGPT、GitHub Copilot、Cursor 等)。
>
> **使用方式**:将本文档作为上下文提供给 AI,或在对话开头粘贴。
>
> **核心原则**:优先遵循已有代码的风格;本文档描述的是偏好,不是必须逐条套用的模板。
---
## 一、技术栈
```
NuGet: Simcu.SimApi
.NET 8 / 9 / 10
C# 12 / 14
Nullable: enable
ImplicitUsings: enable
```
---
## 二、SimApi 核心概念(必读)
### 2.1 响应格式
**所有接口统一输出 JSON,HTTP 状态码始终 200,错误信息在 `code` 字段**
```json
{ "code": 200, "message": "成功", "data": { ... } }
```
不要用 HTTP 4xx/5xx 表达业务错误。
### 2.2 常见错误(AI 容易犯的错)
| ❌ 错误 | ✅ 正确 |
|---------|---------|
| `SupportedMethod` 写多个方法 | 默认仅 `POST`,按需显式添加 |
| `WorkerNum = 50` | 默认是 `5` |
| 存储路径不加斜杠 `/avatars/file.jpg` | 路径必须以 `/` 开头 |
| `s.Endpoint = "http://minio:9000/"` | `ServeUrl`/`Endpoint` **不能以 `/` 结尾** |
| `synapse.PublishEvent(...)` | 方法名是 `synapse.Event(...)` |
| `synapse.CallRpcAsync(...)` | 方法名是 `synapse.Rpc<T>(...)` |
| HTTP 状态码 4xx/5xx 表示错误 | **所有错误均 HTTP 200**,错误在 JSON `code` 字段 |
| `SimApiStorageOptions = Configuration.GetSection(...)` | 用 `options.ConfigureSimApiStorage(s => {...})` |
| `[HttpGet]` / `[HttpPut]` / `[HttpDelete]` | **默认仅 POST**,其他方法需在 `SupportedMethod` 显式添加 |
### 2.3 异常处理流程
```
请求进入
└─ SimApiExceptionMiddleware(捕获所有异常 → HTTP 200 + code 字段)
└─ SimApiAuthMiddleware(解析 Token
└─ [SimApiSign] Filter
└─ [SimApiAuth] Filter
└─ OnActionExecuting(模型验证 → code 400
└─ Action 执行
└─ SimApiResponseFilter(封装响应)
```
---
## 三、C# 语言特性偏好
### 3.1 命名空间
使用**文件范围命名空间**,不用花括号块:
```csharp
// ✅
namespace MyApp.Controllers;
// ❌
namespace MyApp.Controllers { }
```
### 3.2 主构造函数(依赖注入)
使用**主构造函数**注入依赖,不写传统构造函数:
```csharp
// ✅
public class OrderController(DataContext db) : SimApiBaseController
{
}
// ❌
public class OrderController : SimApiBaseController
{
private readonly DataContext _db;
public OrderController(DataContext db) { _db = db; }
}
```
### 3.3 集合表达式
优先 `[]`,避免冗余的 `new`
```csharp
// ✅
string[] tags = [];
string[] roles = ["admin", "manager"];
// ❌
var tags = new string[] { };
var roles = new string[] { "admin", "manager" };
```
### 3.4 字符串
优先字符串插值,不用 `string.Format`
```csharp
// ✅
var msg = $"用户 {user.Name} 不存在";
// ❌
var msg = string.Format("用户 {0} 不存在", user.Name);
```
### 3.5 Null 处理
```csharp
var key = app?.Key; // 安全访问
var name = user?.Name ?? "匿名"; // 空合并
config ??= new Dictionary<string, string>(); // 空合并赋值
```
---
## 四、命名规范
| 类型 | 规则 | 示例 |
|------|------|------|
| 类、接口、枚举 | PascalCase | `AdminController``ResPermission` |
| 方法名 | PascalCase | `UserList``ApplicationEdit` |
| 属性名 | PascalCase | `AccountId``LicenseTotal` |
| 私有字段 | `_camelCase`(如有) | `_logger` |
| 局部变量、参数 | camelCase | `var user``var appId` |
| 常量 | PascalCase | `MaxRetryCount``DefaultRole` |
| 路由路径 | 全小写 + 连字符 | `/device/refresh-context` |
| 配置键 | PascalCase:PascalCase | `"Sms:Templates:Verify"` |
| Redis 缓存 Key | `模块:子类型:标识` | `"Sms:Verify:登陆:手机号"` |
---
## 五、项目目录结构
推荐**极简扁平化**,无 Service 层、无 Repository 层:
```
项目名/
├── Controllers/ # 控制器(含业务逻辑)
│ └── Dtos/ # 请求/响应 DTO
├── Models/ # EF Core 实体 + DataContext
├── Helpers/ # 工具类 / 框架扩展点
├── Migrations/ # EF Core 迁移(自动生成,勿手改)
└── Program.cs # 入口 + DI + 中间件(无 Startup.cs
```
业务逻辑直接在 Controller 中通过 `db`EF Core DbContext)操作数据库。可复用的横切逻辑抽取到 `Helpers/`
> 如果项目较复杂,也可以选择标准分层(Controllers → Services → Models),但需在项目内保持一致,不要混用。
---
## 六、Program.cs 规范
使用顶级语句(无 `Main` 方法、无 `Startup` 类):
```csharp
var builder = WebApplication.CreateBuilder(args);
// 1. SimApi 框架配置
builder.Services.AddSimApi(options =>
{
options.RedisConfiguration = builder.Configuration.GetConnectionString("Redis");
options.EnableSimApiAuth = true; // 按需开启
options.EnableSimApiDoc = true; // 按需开启
options.EnableSimApiStorage = false; // 按需开启
options.EnableJob = false; // 按需开启
options.EnableSynapse = false; // 按需开启
// Swagger 配置
options.ConfigureSimApiDoc(doc =>
{
doc.DocumentTitle = "接口文档";
doc.ApiGroups = [
new("api", "公共接口"),
new("admin", "管理接口")
];
doc.SupportedMethod = [SubmitMethod.Post]; // 默认仅 POST
});
// 存储配置(按需)
// options.ConfigureSimApiStorage(s => { ... });
});
// 2. 数据库
builder.Services.AddDbContext<DataContext>(opt =>
opt.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
// 3. 框架扩展点(用接口注册)
builder.Services.AddScoped<AesBodyProviderBase, AesBodyProvider>();
builder.Services.AddScoped<SimApiSignProviderBase, SimApiSignProvider>();
// 4. 项目自定义服务
builder.Services.AddScoped<ResPermission>();
builder.Services.AddSingleton<JsonSchemaHelper>();
var app = builder.Build();
// 5. 启动时自动迁移(同步写法)
app.Services.CreateScope().ServiceProvider
.GetRequiredService<DataContext>().Database.Migrate();
// 6. 框架中间件
app.UseSimApi();
app.Run();
```
### SimApiOptions 常用配置
```csharp
options.RedisConfiguration = "localhost:6379"; // Redis(多模块共用)
options.EnableSimApiAuth = false; // Token 认证
options.EnableSimApiDoc = false; // Swagger
options.EnableSimApiStorage = false; // S3 存储
options.EnableJob = false; // Hangfire 任务调度
options.EnableSynapse = false; // MQTT 通信
options.EnableCoceSdk = false; // Coce 统一身份
// 以下默认 true,通常不需要改:
options.EnableCors = true;
options.EnableSimApiException = true;
options.EnableSimApiResponseFilter = true;
options.EnableForwardHeaders = true;
options.EnableLowerUrl = true;
options.EnableVersionUrl = true;
options.EnableLogger = true;
```
---
## 七、控制器规范
### 7.1 基类与依赖注入
所有 Controller 继承 `SimApiBaseController`,依赖通过**主构造函数**注入:
```csharp
[SimApiAuth]
public class DeviceController(DataContext db) : SimApiBaseController
{
}
```
### 7.2 路由规则
**默认全部使用 POST**(除非在 `SupportedMethod` 中显式添加其他方法):
```csharp
// 方法上写完整路径
[HttpPost("/device/list")]
[HttpPost("/application/refresh-key")]
// 类上写前缀,方法上写相对路径
[Route("/platform")]
public class PlatformController(DataContext db) : SimApiBaseController
{
[HttpPost("device/detail")] // 最终路由:/platform/device/detail
[HttpPost("bot/generate")] // 最终路由:/platform/bot/generate
}
```
路由路径全小写,多词用连字符 `-` 分隔。
### 7.3 鉴权 Attribute
| Attribute | 用途 |
|-----------|------|
| `[SimApiAuth]` | 要求登录用户 |
| `[SimApiAuth("admin")]` | 要求 admin 角色 |
| `[SimApiAuth("admin,manager")]` | 逗号分隔,OR 关系 |
| `[SimApiSign(KeyProvider = typeof(XxxProvider))]` | API 签名验证 |
> 鉴权 Attribute 写在 **Controller 类** 上,不写在方法上。
### 7.4 接口分组与文档
```csharp
[ApiExplorerSettings(GroupName = "platform")]
[SimApiDoc("设备", "获取设备详情")]
[HttpPost("device/detail")]
public Device DeviceDetail(...)
```
### 7.5 方法返回值
| 场景 | 返回类型 |
|------|----------|
| 写操作(新增/修改/删除) | `void`(框架自动返回 `{"code":200}` |
| 单条查询 | 直接返回 Entity(如 `Account``Device` |
| 列表查询 | `Entity[]`(数组,不用 `List<T>` |
| 分页查询 | `PageResponse<Entity[]>` |
| 有状态响应 | `SimApiBaseResponse` |
| 复杂组合响应 | 对应 DTO |
> **不使用** `ActionResult<T>` 或 `IActionResult`(除非使用 `[AesBody]` 等框架 Attribute)。
### 7.6 方法参数
```csharp
// 普通请求体
[FromBody] DeviceDto.SerialAddRequest request
// AES 加密请求体
[AesBody(KeyProvider = typeof(AesBodyProvider))] BotDto.BotChatRequest request
// 查询字符串(直接写,不加 Attribute)
string appId
```
### 7.7 错误处理
使用基类的 `ErrorWhen` 系列方法,**不手动 throw、不返回错误码**:
```csharp
ErrorWhenNull(entity); // null 则报错(默认 404
ErrorWhenNull(entity, 404, "用户不存在"); // 自定义状态码和消息
ErrorWhen(condition, 400, "已经共享过了"); // condition 为 true 则报错
ErrorWhenFalse(condition, 403, "你无权操作"); // condition 为 false 则报错
```
在 Controller 外部(如 Helper 中)需要抛出异常时,使用 `SimApiException`
```csharp
throw new SimApiException(404, "App不存在");
throw new SimApiException(403, "没有权限修改对应资源");
```
### 7.8 当前登录信息
```csharp
// 通过基类属性获取(需 EnableSimApiAuth
var userId = LoginInfo?.Id;
var userRole = LoginInfo?.Type; // string[]
// 权限检查示例
ErrorWhen(!LoginInfo.Type.Contains("admin"), 403, "需要管理员权限");
```
### 7.9 私有辅助方法
Controller 内部可复用的逻辑提取为 `private` 方法,不独立成 Service
```csharp
private void CheckAppId(string appId)
{
ErrorWhen(!db.Applications.Any(x => x.AccountId == LoginInfo.Id && x.Id == appId), 403, "无权操作");
}
```
---
## 八、DTO 规范
### 8.1 组织方式
DTO 文件放在 `Controllers/Dtos/`,按业务域命名 `XxxDto.cs`。使用嵌套容器类:
```csharp
namespace MyApp.Controllers.Dtos;
public abstract class AdminDto
{
public class UserEditRequest
{
public required string Id { get; set; }
public required string Name { get; set; }
}
public class ApplicationListRequest : SimApiBasePageRequest
{
public string? Keyword { get; set; }
}
}
```
### 8.2 命名规则
| 类型 | 格式 | 示例 |
|------|------|------|
| 请求 DTO | `[动作]Request` | `UserEditRequest``DeviceSerialAddRequest` |
| 响应 DTO | `[动作]Response` | `GenerateResponse``TokenResponse` |
| 数据载体 | `[含义]Data` | `GenerateData``AgentItem` |
引用时用全限定名:`AdminDto.UserEditRequest``PlatformDto.GenerateResponse`
### 8.3 属性规则
```csharp
public class DeviceSerialAddRequest
{
public required string Verify { get; set; } // 必填
public required string AppId { get; set; }
public required string Name { get; set; }
[Range(1, 10000)] public required int Num { get; set; } // 范围校验
public string? Remark { get; set; } // 可选
public int Status { get; set; } = 1; // 有默认值
}
```
### 8.4 框架内置通用 DTO(优先复用)
| 框架 DTO | 用途 |
|----------|------|
| `SimApiStringIdOnlyRequest` | 只有 `Id` 字段的请求 |
| `SimApiOneFieldRequest<T>` | 只有一个 `Data` 字段的请求 |
| `SimApiBasePageRequest` | 分页请求基类(含 `Page``Count` |
| `SimApiBaseResponse` | 通用状态响应(可传 code + message |
| `SimApiBaseResponse<T>` | 带数据的响应 |
| `PageResponse<T>` | 分页响应(含 `Total``Page``Count``List` |
---
## 九、Entity 规范
### 9.1 基类
所有实体继承 `SimApiBaseModel`(自动提供 `Id``CreatedAt``UpdatedAt`):
```csharp
using SimApi.Models;
namespace MyApp.Models;
public class Account : SimApiBaseModel
{
public required string Name { get; set; }
public required string Username { get; set; }
public string? Password { get; set; }
public required string Role { get; set; } = "user";
public int Status { get; set; } = 1;
}
```
### 9.2 对象映射(MapData
`SimApiBaseModel` 提供 `MapData` 方法,用于 DTO ↔ Entity 映射:
```csharp
// 跳过 Id/CreatedAt/UpdatedAt,映射同名同类型且源值不为 null 的属性
entity.MapData(dto);
// 映射所有字段
entity.MapData(dto, mapAll: true);
// 只映射指定字段
entity.MapData(dto, new[] { "Name", "Email" });
// 手动更新 UpdatedAt
entity.UpdateTime();
```
### 9.3 属性规则
- 必填字段用 `required`,可选字段用 `?`,有默认值的直接赋值
- 外键命名:`[关联实体]Id`,如 `AccountId``AppId``ServiceId`
- **不配置导航属性**,不配置 EF Fluent API,依赖 Convention 自动映射
### 9.4 DataContext
只定义 DbSet,不做任何 Fluent API 配置:
```csharp
public class DataContext(DbContextOptions<DataContext> options) : DbContext(options)
{
public required DbSet<Account> Accounts { get; set; }
public required DbSet<Application> Applications { get; set; }
public required DbSet<Device> Devices { get; set; }
}
```
---
## 十、EF Core 查询风格
```csharp
// 列表查询(排序 + ToArray
db.Accounts.OrderBy(x => x.CreatedAt).ToArray();
// 动态条件查询(AsQueryable 后追加 Where
var query = db.Devices
.Where(x => x.ApplicationId == appId)
.OrderBy(x => x.CreatedAt)
.AsQueryable();
if (!string.IsNullOrEmpty(request.Serial))
query = query.Where(x => x.Serial == request.Serial);
// 分页查询(框架扩展方法 Paginate)
var list = query.Paginate(request.Page, request.Count).ToArray();
var total = query.Count();
return new PageResponse<Device[]> { List = list, Total = total, Page = request.Page, Count = request.Count };
// 单条查询
db.Accounts.Find(id); // 主键用 Find
db.Accounts.FirstOrDefault(x => x.Username == username); // 其他条件用 FirstOrDefault
// 写操作
db.Add(entity); // 新增
db.Update(entity); // 修改
db.Remove(entity); // 删除
db.SaveChanges(); // 统一在所有操作完成后调用一次
// 存在性判断(不用 Count
db.AppServices.Any(x => x.ServiceId == request.Id)
```
---
## 十一、框架扩展点(Helpers/
### 11.1 AES 加密请求体
实现 `AesBodyProviderBase`,提供解密密钥:
```csharp
public class AesBodyProvider(DataContext db) : AesBodyProviderBase
{
public override string? AppIdName { get; set; } = "appId";
public override string? GetKey(string? appId)
{
var application = db.Applications.Find(appId);
return application?.Key;
}
}
```
客户端提交格式:`{"data": "Base64(AES-256-CBC 加密 JSON)"}`
静态工具类(无需注入):
```csharp
string cipher = SimApiAesUtil.Encrypt("明文", "任意长度密钥");
string plain = SimApiAesUtil.Decrypt(cipher, "任意长度密钥");
```
### 11.2 API 签名验证
实现 `SimApiSignProviderBase`
```csharp
public class SimApiSignProvider(DataContext db) : SimApiSignProviderBase
{
public override string? AppIdName { get; set; } = "appId";
public override string TimestampName { get; set; } = "timestamp";
public override string NonceName { get; set; } = "nonce";
public override string SignName { get; set; } = "sign";
public override int QueryExpires { get; set; } = 5;
public override bool DuplicateRequestProtection { get; set; } = true;
public override string[] SignFields { get; set; } = ["userId"];
public override string? GetKey(string? appId)
{
return db.Applications.Find(appId)?.SecretKey;
}
}
```
> 扩展点用**接口注册**`builder.Services.AddScoped<AesBodyProviderBase, AesBodyProvider>()`
### 11.3 Helper 使用原则
Helper 仅用于以下场景,**不承担 CRUD 业务逻辑**:
1. **框架扩展点**:继承 `XxxProviderBase` 并 override 方法
2. **横切关注点**:权限校验、短信发送
3. **纯工具静态类**:无状态工具方法
4. **有状态单例/Scoped 服务**:如 JSON Schema 验证
---
## 十二、框架功能模块
### 12.1 认证(SimApiAuth
```csharp
// Program.cs
options.EnableSimApiAuth = true;
options.RedisConfiguration = "..."; // 必须
// Token 通过 Header 传入:Token: <value>
// DI 注入 SimApiAuth 服务
public MyController(SimApiAuth auth) { }
// 登录
string token = auth.Login(loginItem); // 自动生成 GUID token
string token = auth.Login(loginItem, "custom-token");
auth.Update(loginItem, token);
// 查询/退出
SimApiLoginItem? info = auth.GetLogin(token);
auth.Logout(token);
// SimApiLoginItem 结构
// { Id: string, Type: string[], Meta: Dictionary<string,string>, Extra: object? }
```
自动路由(开启 `EnableSimApiAuth` 后可用):
- `POST /auth/check` — 检测登录状态
- `POST /auth/logout` — 退出登录
- `POST /user/info` — 获取用户信息(需登录)
### 12.2 对象存储(SimApiStorage
```csharp
// Program.cs
options.EnableSimApiStorage = true;
options.ConfigureSimApiStorage(s =>
{
s.Endpoint = "http://minio:9000"; // 不能以 / 结尾
s.AccessKey = "admin";
s.SecretKey = "pass";
s.Bucket = "my-bucket";
s.ServeUrl = "http://cdn.example.com/my-bucket"; // 不能以 / 结尾
});
// DI 注入
public MyController(SimApiStorage storage) { }
// 路径必须以 / 开头
storage.GetUploadUrl("/avatars/user1.jpg"); // 返回上传地址和下载地址
storage.GetDownloadUrl("/files/doc.pdf"); // 默认 10 分钟过期
storage.GetDownloadUrl("/files/doc.pdf", expire: 3600);
storage.UploadFile("/path/file.jpg", stream, "image/jpeg"); // 服务端直传
storage.FullUrl("/path/file"); // 路径转完整 URL
storage.GetPath("http://cdn.../my-bucket/path/file"); // URL 转路径
```
### 12.3 Redis 缓存(SimApiCache
```csharp
public MyService(SimApiCache cache) { }
cache.Set("key", value); // 永不过期
cache.Set("key", value, new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
string? raw = cache.Get("key"); // 原始字符串
int? val = cache.Get<int>("key"); // 反序列化
// key 自动加前缀 SimApi:Cache:
```
### 12.4 任务调度(Hangfire
```csharp
// Program.cs
options.EnableJob = true;
options.ConfigureSimApiJob(job =>
{
job.DashboardUrl = "/jobs";
job.DashboardAuthUser = "admin";
job.DashboardAuthPass = "Admin@123!";
job.Servers = [
new SimApiJobServerConfig { Queues = ["default"], WorkerNum = 5 },
new SimApiJobServerConfig { Queues = ["email"], WorkerNum = 2 }
];
});
// 使用
BackgroundJob.Enqueue(() => myService.DoWork());
BackgroundJob.Schedule(() => myService.DoWork(), TimeSpan.FromMinutes(5));
RecurringJob.AddOrUpdate("job-id", () => myService.DoWork(), Cron.Daily);
var id = BackgroundJob.Enqueue(() => Step1());
BackgroundJob.ContinueJobWith(id, () => Step2());
```
### 12.5 MQTT 通信(Synapse
```csharp
// Program.cs
options.EnableSynapse = true;
options.ConfigureSimApiSynapse(s =>
{
s.Websocket = "ws://mqtt:8083/mqtt"; // WebSocket 连接(不是 RabbitMQ
s.Username = "user";
s.Password = "pass";
s.SysName = "my-system";
s.AppName = "order-service";
s.AppId = "instance-001";
s.RpcTimeout = 3;
});
// DI 注入
public MyService(Synapse synapse) { }
// 发布事件
synapse.Event("order/created", new { OrderId = 1 });
// RPC 调用(同步,返回 SimApiBaseResponse<T>
var res = synapse.Rpc<UserDto>("user-service", "GetUserInfo", new { Id = 1 });
// RPC 方法内部抛错
synapse.RpcError(400, "参数错误");
synapse.RpcErrorWhen(id <= 0, 400, "ID 无效");
// 事件处理器(自动扫描注册)
public class OrderEventHandler
{
[SynapseEvent("order/+/status")] // 支持 + 和 # 通配符
public void OnOrderStatus(string eventName, OrderStatusDto data) { }
}
// RPC 服务(自动扫描注册)
public class UserRpcService
{
[SynapseRpc] // 注册为 "UserRpcService.GetUserInfo"
public UserDto GetUserInfo(GetUserRequest req) { return ...; }
[SynapseRpc("customName")]
public ResultDto DoSomething(RequestDto req, Dictionary<string, string> headers) { }
}
```
### 12.6 HTTP 客户端(SimApiHttpClient
```csharp
var client = new SimApiHttpClient(appId: "myapp", appKey: "secret")
{
Server = "https://api.example.com",
};
var r = client.SignQuery<T>("/api/user", body, queries); // 仅签名
var r = client.AesQuery<T>("/api/user", body); // 仅 AES 加密
var r = client.AesSignQuery<T>("/api/user", body, queries); // AES + 签名
```
### 12.7 工具类(SimApiUtil,全部静态)
```csharp
DateTime cst = SimApiUtil.CstNow; // UTC+8 当前时间
double ts = SimApiUtil.TimestampNow; // 秒级 Unix 时间戳
string md5 = SimApiUtil.Md5("src"); // 32位 MD5
string json = SimApiUtil.Json(obj); // camelCase,中文不转义
bool ok = SimApiUtil.CheckCell("13800138000"); // 手机号验证
```
---
## 十三、配置文件规范
`appsettings.json` 只保留框架默认值:
```json
{
"Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } },
"AllowedHosts": "*"
}
```
`appsettings.Development.json` 存放开发环境实际配置(不提交到 Git):
```json
{
"ConnectionStrings": {
"Default": "Host=...;Database=...;Username=...;Password=...",
"Redis": "host:port,defaultDatabase=N"
},
"Sms": { "Account": "...", "Password": "..." }
}
```
配置读取:
```csharp
builder.Configuration.GetConnectionString("Default")
config["Gateway:Key"]
config.GetSection("Sms").GetSection("Templates")["verify"]
```
---
## 十四、注释规范
- **公有 API / 方法**:写 XML 文档注释
- **私有方法**:逻辑简单可不写;复杂逻辑写行内注释说明**为什么**
- **不要写废话注释**
```csharp
/// <summary>
/// 根据邮箱查询用户,不存在返回 null。
/// </summary>
public Account? FindByEmail(string email)
=> db.Accounts.FirstOrDefault(x => x.Email == email);
// ❌ 废话注释
// 查询用户
var user = db.Accounts.Find(id);
// ✅ 有意义的注释
// EF Core 的 Find 会优先命中一级缓存
var user = db.Accounts.Find(id);
```
---
## 十五、禁止事项
以下模式在使用 SimApi 框架时**明确禁止**
| ❌ 禁止 | ✅ 正确做法 |
|---------|------------|
| 使用 HTTP 4xx/5xx 表达业务错误 | HTTP 200 + JSON `code` 字段 |
| `throw new Exception(message)` | `ErrorWhen` 系列或 `SimApiException` |
| 新建 Service / Repository 层(除非项目明确需要) | Controller 直接操作 DbContext |
| 使用 `ActionResult<T>` / `IActionResult` | 直接返回 Entity / `void` / `SimApiBaseResponse` |
| 在 Controller 方法上加鉴权 Attribute | 加在 Controller 类上 |
| 在 Entity 中配置导航属性或 EF Fluent API | 依赖 Convention 自动映射 |
| 在 DbContext 中写 `OnModelCreating`(除非需要全局过滤等) | 只定义 DbSet |
| 花括号块命名空间 | 文件范围命名空间 |
| 传统构造函数注入 | 主构造函数 |
| `new List<T>()` 初始化空集合 | `[]` 集合表达式 |
| `Count() > 0` 判断存在 | `Any()` |
| `ToList()` 再转数组 | 直接 `ToArray()` |
| `string.IsNullOrEmpty` 判断必填入参 | `required` 修饰符 + 模型验证 |
| 全局 `catch (Exception e) { log; return null; }` | 让异常冒泡,由 SimApiExceptionMiddleware 处理 |