Compare commits

...
14 Commits
42 changed files with 1772 additions and 2739 deletions
-574
View File
@@ -1,574 +0,0 @@
# 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(封装响应)
```
+9 -8
View File
@@ -1,9 +1,11 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using SimApi.Communications;
using SimApi.Exceptions;
using SimApi.Interfaces;
using static SimApi.Helpers.SimApiError;
namespace SimApi.Attributes;
@@ -37,17 +39,16 @@ public class SimApiAuthAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
{
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
//检测是否登录
if (loginInfo == null)
var token = (string)context.HttpContext.Items["LoginToken"]!;
ErrorWhenNull(loginInfo, 401);
var checkers = context.HttpContext.RequestServices.GetServices<ISimApiAuthChecker>();
foreach (var checker in checkers)
{
throw new SimApiException(401);
checker.Run(loginInfo, token);
}
if (Types == null) return;
//检测用户类型
if (!Types.Intersect(loginInfo.Type).Any())
{
throw new SimApiException(403);
}
ErrorWhenFalse(Types.Intersect(loginInfo.Type).Any(), 403);
}
}
+169
View File
@@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using SimApi.Communications;
using static SimApi.Helpers.SimApiError;
namespace SimApi.AuthGate;
public class SimApiAuthGate(SimApiAuthGateClient simapi)
{
#region AuthGate公开接口
/// <summary>
/// 委托AuthCenter进行应用签名验证
/// </summary>
/// <param name="appId"></param>
/// <param name="timestamp"></param>
/// <param name="nonce"></param>
/// <param name="sign"></param>
public void VerifySign(string appId, string timestamp, string nonce, string sign)
{
var http = new HttpClient();
var url = $"{simapi.Server}/api/auth/sign/verify?appId={appId}&timestamp={timestamp}&nonce={nonce}&sign={sign}";
var result = http.PostAsJsonAsync(url, new { }).Result;
var resp = result.Content.ReadFromJsonAsync<SimApiBaseResponse>().Result;
ErrorWhenNull(resp, 400, "签名验证失败");
ErrorWhenFalse(resp.Code == 200, 400, "签名验证失败");
}
/// <summary>
/// 根据关键字,搜索用户Profile,参数支持精准ID,用户手机号,用户邮箱,Profile名称模糊搜索
/// </summary>
/// <param name="keyword"></param>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <returns></returns>
public SimApiAuthGateDto.AppAndProfileItem[]? ProfileSearch(string keyword, int skip = 0, int take = 20)
{
return simapi.SignQuery<SimApiAuthGateDto.AppAndProfileItem[]>("/api/auth/profile/search",
new { keyword, skip, take });
}
/// <summary>
/// 通过id,可以批量获取用户的基本信息
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public SimApiAuthGateDto.AppAndProfileItem[]? ProfileList(string[] ids)
{
return simapi.SignQuery<SimApiAuthGateDto.AppAndProfileItem[]>("/api/auth/profile/list", new { ids });
}
#endregion
#region AuthGate内部应用专用 - :
/// <summary>
/// 获取是否为App的拥有者
/// </summary>
/// <param name="profileId"></param>
/// <param name="applicationId"></param>
/// <returns></returns>
public bool CheckIsAppOwner(string profileId, string applicationId)
{
return simapi.SignQuery<bool>("/api/auth/internal/apps/check-owner", new
{
ProfileId = profileId,
AppId = applicationId,
});
}
/// <summary>
/// 获取应用列表,根据用户profileId 和 提供的appIds
/// </summary>
/// <param name="profileId"></param>
/// <param name="appIds"></param>
/// <returns></returns>
public SimApiAuthGateDto.AppAndProfileItem[]? GetAppList(string profileId, IEnumerable<string> appIds)
{
return simapi.SignQuery<SimApiAuthGateDto.AppAndProfileItem[]>("/api/auth/internal/apps/related", new
{
ProfileId = profileId,
AllowedAppIds = appIds,
});
}
#endregion
#region
/// <summary>
/// 获取登录授权CODE
/// </summary>
/// <param name="scene"></param>
/// <param name="data"></param>
/// <param name="backUrl"></param>
/// <returns></returns>
public SimApiAuthGateDto.GetCodeResponse GetAuthCode(string? scene = null, Dictionary<string, object>? data = null,
string? backUrl = null)
{
var code = simapi.SignQuery<string>("/api/auth/confirm/code",
new { scene, data, backUrl });
return new SimApiAuthGateDto.GetCodeResponse()
{
Code = code!,
Server = simapi.Server,
FullUrl = $"{simapi.Server}/auth?code={code}"
};
}
/// <summary>
/// 使用code获取登录信息
/// </summary>
/// <param name="code"></param>
/// <param name="scene"></param>
/// <returns></returns>
public SimApiAuthGateDto.AuthInfoResponse GetAuthInfo(string code, string? scene = null)
{
var resp = simapi.SignQuery<SimApiAuthGateDto.AuthInfoResponse>("/api/auth/confirm/get", new { code });
ErrorWhenNull(resp, 400232, "登录信息获取失败");
ErrorWhen(resp.Scene != scene, 403003, "登录场景不匹配");
return resp;
}
#endregion
#region
/// <summary>
/// 获取安全验证代码
/// </summary>
/// <param name="scene"></param>
/// <param name="userId"></param>
/// <param name="data"></param>
/// <param name="backUrl"></param>
/// <returns></returns>
public SimApiAuthGateDto.GetCodeResponse GetConfirmCode(string scene, string userId,
Dictionary<string, object>? data = null,
string? backUrl = null)
{
var code = simapi.SignQuery<string>("/api/auth/confirm/code",
new { scene, data, backUrl, profileId = userId });
return new SimApiAuthGateDto.GetCodeResponse()
{
Code = code!,
Server = simapi.Server,
FullUrl = $"{simapi.Server}/confirm?code={code}"
};
}
/// <summary>
/// 使用安全验证code 获取验证结果
/// </summary>
/// <param name="code"></param>
/// <param name="scene"></param>
/// <param name="userId"></param>
/// <returns></returns>
public SimApiAuthGateDto.ConfirmResponse Confirm(string code, string scene, string? userId = null)
{
var resp = simapi.SignQuery<SimApiAuthGateDto.ConfirmResponse>("/api/auth/confirm/get", new { code });
ErrorWhenNull(resp, 403001, "安全确认码无效");
ErrorWhen(resp.ProfileId != userId, 403002, "安全确认身份不匹配");
ErrorWhen(resp.Scene != scene, 403003, "安全确认场景不匹配");
return resp;
}
#endregion
}
+11
View File
@@ -0,0 +1,11 @@
using SimApi.Configurations;
using SimApi.Helpers;
namespace SimApi.AuthGate;
public class SimApiAuthGateClient(SimApiOptions apiOptions) : SimApiHttpClient
{
public override string Server { get; init; } = apiOptions.SimApiAuthGateOptions.Server ?? string.Empty;
public override string AppId { get; init; } = apiOptions.SimApiAuthGateOptions.AppId ?? string.Empty;
public override string AppKey { get; init; } = apiOptions.SimApiAuthGateOptions.AppKey ?? string.Empty;
}
+40
View File
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
namespace SimApi.AuthGate;
public class SimApiAuthGateDto
{
public class AppAndProfileItem
{
public string Id { get; set; } = "";
public string Name { get; set; } = "";
public string? Image { get; set; }
public string? Description { get; set; }
}
public class ConfirmResponse
{
public required string ApplicationId { get; set; }
public required string ProfileId { get; set; }
public string? Scene { get; set; }
public Dictionary<string, object>? Data { get; set; }
}
public class AuthInfoResponse
{
public string? Scene { get; set; }
public Dictionary<string, object>? Data { get; set; }
public required string ProfileId { get; set; }
public required string Name { get; set; }
public string? Image { get; set; }
public string? Description { get; set; }
}
public class GetCodeResponse
{
public required string Code { get; set; }
public required string Server { get; set; }
public required string FullUrl { get; set; }
}
}
+34
View File
@@ -0,0 +1,34 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Helpers;
namespace SimApi.AuthGate;
public class SimApiAuthGateMiddleware(RequestDelegate next, ILogger<SimApiAuthGateMiddleware> logger)
{
public Task Invoke(HttpContext httpContext, SimApiOptions simApiOptions)
{
if (httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Auth", out var auth) &&
httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Time", out var time) &&
httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Sign", out var sign))
{
var signStr =
$"appId={simApiOptions.SimApiAuthGateOptions.AppId}&auth={auth}&time={time}&appKey={simApiOptions.SimApiAuthGateOptions.AppKey}";
logger.LogDebug($"签名字符串 => {signStr}");
if (SimApiUtil.Md5(signStr) == sign && !string.IsNullOrEmpty(auth))
{
var login = SimApiUtil.Base64Decode<SimApiLoginItem>(auth!);
httpContext.Items.Add("LoginInfo", login);
}
else
{
logger.LogDebug("签名不匹配");
}
}
return next(httpContext);
}
}
+45
View File
@@ -0,0 +1,45 @@
using Microsoft.Extensions.Logging;
using static SimApi.Helpers.SimApiError;
namespace SimApi.AuthGate;
public class SimApiIam(SimApiAuthGateClient simapi, ILogger<SimApiIam> logger)
{
/// <summary>
/// 向Iam注册权限
/// </summary>
/// <param name="permissions"></param>
public void RegisterPermissions(SimApiIamDto.PermissionItem[] permissions)
{
var log = $"检测到 {permissions.Length} 个权限接口,正在注册..: ";
foreach (var permission in permissions)
{
log += $"\n |- {permission.Identifier} => [{permission.Group}]{permission.Name} ({permission.Description})";
}
logger.LogInformation(log);
simapi.SignQuery<string>("/api/iam/permission/register", new { permissions });
logger.LogInformation("权限注册完成");
}
/// <summary>
/// 获取拥有的权限标识数组
/// </summary>
/// <param name="profileId"></param>
/// <returns></returns>
public string[] GetPermissionOwned(string profileId)
{
return simapi.SignQuery<string[]>("/api/iam/permission/owned", new { profileId }) ?? [];
}
/// <summary>
/// 检测profileId是否有这个权限
/// </summary>
/// <param name="profileId"></param>
/// <param name="permission"></param>
public void CheckPermission(string profileId, string permission)
{
var ok = simapi.SignQuery<bool>("/api/iam/permission/check", new { profileId, permission });
ErrorWhen(!ok, 403, "没有该权限");
}
}
+12
View File
@@ -0,0 +1,12 @@
namespace SimApi.AuthGate;
public class SimApiIamDto
{
public class PermissionItem
{
public required string Identifier { get; init; }
public required string Name { get; init; }
public required string Group { get; init; }
public required string Description { get; init; }
}
}
-235
View File
@@ -1,235 +0,0 @@
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
@@ -1,15 +0,0 @@
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
@@ -1,51 +0,0 @@
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
@@ -1,43 +0,0 @@
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
@@ -1,9 +0,0 @@
using System.Collections.Generic;
using SimApi.Communications;
namespace SimApi.CoceSdk;
public interface ICoceLoginProcessor
{
SimApiLoginItem Process(SimApiLoginItem loginItem, GroupInfo[] groups);
}
+2 -2
View File
@@ -27,11 +27,11 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
{ 400, "参数错误" },
{ 401, "需要登录" },
{ 403, "无权访问" },
{ 404, "接口不存在" },
{ 404, "请求资源不存在" },
{ 500, "服务器错误" }
};
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误"))
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误代码"))
{
}
+1 -1
View File
@@ -10,5 +10,5 @@ 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; }
public Dictionary<string, object?> Extra { get; set; } = [];
};
+14
View File
@@ -0,0 +1,14 @@
namespace SimApi.Configurations;
public class SimApiAuthGateOptions
{
public string? Server { get; set; }
public string? AppId { get; set; }
public string? AppKey { get; set; }
/// <summary>
/// 开启则使用内部网关透传的Middleware
/// 注意: 只有内部应用需要开启这个,也就是api通过内部网关代理后
/// </summary>
public bool UseMiddleware { get; set; }
}
+6
View File
@@ -0,0 +1,6 @@
namespace SimApi.Configurations;
public class SimApiExceptionOptions
{
public int[] SkipStatusCodes = [200, 301, 302];
}
@@ -0,0 +1,8 @@
namespace SimApi.Configurations;
public class SimApiHttpClientOptions
{
public string Server { get; set; } = string.Empty;
public string AppId { get; set; } = string.Empty;
public string AppKey { get; set; } = string.Empty;
}
+26 -12
View File
@@ -1,5 +1,4 @@
using System;
using SimApi.CoceSdk;
namespace SimApi.Configurations;
@@ -19,9 +18,9 @@ public class SimApiOptions
public bool EnableSimApiAuth { get; set; }
/// <summary>
/// 是否使用CoceSdk
/// 启用SimApi网关授权, 基于上层网关透传的身份令牌验证
/// </summary>
public bool EnableCoceSdk { get; set; }
public bool EnableSimApiAuthGate { get; set; }
/// <summary>
/// 开启S3兼容的存储系统。
@@ -46,9 +45,6 @@ public class SimApiOptions
/// </summary>
public bool EnableCors { get; set; } = true;
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
/// <summary>
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
/// default: true
@@ -81,7 +77,6 @@ public class SimApiOptions
public bool EnableVersionUrl { get; set; } = true;
/// <summary>
/// 启用格式化的 Console Logger
/// default: false
@@ -89,6 +84,9 @@ public class SimApiOptions
public bool EnableLogger { get; set; } = true;
public bool EnableSimApiHttpClient { get; set; } = false;
/// <summary>
/// 配置Job
/// </summary>
@@ -106,16 +104,27 @@ public class SimApiOptions
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
public SimApiAuthGateOptions SimApiAuthGateOptions { get; set; } = new();
public SimApiHttpClientOptions SimApiHttpClientOptions { get; set; } = new();
public SimApiExceptionOptions SimApiExceptionOptions { get; set; } = new();
public void ConfigureSimApiException(Action<SimApiExceptionOptions>? options = null)
{
options?.Invoke(SimApiExceptionOptions);
}
public void ConfigureSimApiHttpClient(Action<SimApiHttpClientOptions>? options = null)
{
options?.Invoke(SimApiHttpClientOptions);
}
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
{
options?.Invoke(SimApiSynapseOptions);
}
public void ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)
{
options?.Invoke(CoceSdkOptions);
}
public void ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)
{
options?.Invoke(SimApiDocOptions);
@@ -130,4 +139,9 @@ public class SimApiOptions
{
options?.Invoke(SimApiJobOptions);
}
public void ConfigureSimApiAuthGate(Action<SimApiAuthGateOptions>? options = null)
{
options?.Invoke(SimApiAuthGateOptions);
}
}
+6 -30
View File
@@ -1,49 +1,25 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.Controllers;
using static SimApiError;
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()
public void Logout()
{
string? token = null;
if (Request.Headers.TryGetValue("Token", out var value))
{
token = value;
auth.Logout(value!);
}
auth.Logout(token!);
return new SimApiBaseResponse();
}
[HttpPost, SimApiAuth]
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
{
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
}
}
+4 -73
View File
@@ -1,10 +1,9 @@
using System.Diagnostics.CodeAnalysis;
using SimApi.Communications;
using SimApi.Communications;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Linq;
using SimApi.Exceptions;
using static SimApi.Helpers.SimApiError;
namespace SimApi.Controllers;
@@ -24,6 +23,8 @@ public class SimApiBaseController : Controller
/// </summary>
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
protected string LoginToken => (string)HttpContext.Items["LoginToken"]!;
/// <summary>
/// 验证请求参数
/// </summary>
@@ -38,74 +39,4 @@ public class SimApiBaseController : Controller
break;
}
}
/// <summary>
/// 错误返回
/// </summary>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
/// <returns></returns>
protected static void Error(int code = 500, string message = "")
{
throw new SimApiException(code, message);
}
/// <summary>
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhen([DoesNotReturnIf(true)] bool condition, int code = 400, string message = "")
{
if (condition)
{
Error(code, message);
}
}
/// <summary>
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenTrue([DoesNotReturnIf(true)] bool condition, int code = 400, string message = "")
{
ErrorWhen(condition, code, message);
}
/// <summary>
/// 如果condition是false 报错
/// </summary>
/// <param name="condition"></param>
/// <param name="code"></param>
/// <param name="message"></param>
protected static void ErrorWhenFalse([DoesNotReturnIf(false)] bool condition, int code = 400, string message = "")
{
ErrorWhen(!condition, code, message);
}
/// <summary>
/// 检测给定的变量是否为NUll
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenNull([NotNull] object? condition, int code = 404, string message = "请求的资源不存在")
{
ErrorWhen(condition == null, code, message);
}
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
protected SimApiBaseResponse<string> UploadFile()
{
return new SimApiBaseResponse<string>();
}
}
+15 -9
View File
@@ -1,7 +1,9 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Helpers;
using static SimApi.Helpers.SimApiError;
namespace SimApi.Controllers;
@@ -14,22 +16,26 @@ public class SimApiCommonController : SimApiBaseController
/// <returns></returns>
[HttpGet("exception/{code:int}")]
[ApiExplorerSettings(IgnoreApi = true)]
public SimApiBaseResponse ExceptionHandler(int code)
public void ExceptionHandler(int code)
{
return new SimApiBaseResponse(code);
Error(code);
}
[HttpPost, HttpGet]
public SimApiBaseResponse<Dictionary<string, string>> Versions()
public Dictionary<string, string> Versions()
{
return new SimApiBaseResponse<Dictionary<string, string>>()
return new Dictionary<string, string>
{
Data = new Dictionary<string, string>
{
{ "SimApi", SimApiUtil.SimApiVersion },
{ "App", SimApiUtil.AppVersion }
}
{ "SimApi", SimApiUtil.SimApiVersion },
{ "App", SimApiUtil.AppVersion }
};
}
/// <summary>
/// 获取已登录用户信息
/// </summary>
/// <returns></returns>
[HttpPost("/user/info"), SimApiAuth, SimApiDoc("认证", "获取已登录用户信息")]
public SimApiLoginItem UserInfo() => LoginInfo;
}
+95 -11
View File
@@ -1,25 +1,41 @@
using System;
using System.Text.Json;
using System.Collections.Generic;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
using StackExchange.Redis;
namespace SimApi.Helpers;
/// <summary>
/// 认证助手
/// </summary>
public class SimApiAuth(IDistributedCache cache)
public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
{
private const string TokenCacheKey = "SimApi:Auth:Token:{token}";
private const string TokenSetCacheKey = "SimApi:Auth:User:{userId}";
private readonly IDatabase _redisDb = redis.GetDatabase();
/// <summary>
/// 登录信息
/// </summary>
/// <param name="loginItem"></param>
/// <param name="expireTime"></param>
/// <param name="token"></param>
/// <returns></returns>
public string Login(SimApiLoginItem loginItem, string? token = null)
public string Login(SimApiLoginItem loginItem, TimeSpan? expireTime = null, string? token = null)
{
expireTime ??= TimeSpan.FromDays(7);
token ??= Guid.NewGuid().ToString();
cache.SetString(token, JsonSerializer.Serialize(loginItem));
var cacheKey = TokenCacheKey.Replace("{token}", token);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.SetAdd(setCacheKey, token);
cache.SetString(cacheKey, SimApiUtil.Json(loginItem),
new DistributedCacheEntryOptions
{
SlidingExpiration = expireTime
});
_redisDb.KeyExpire(setCacheKey, expireTime.Value);
return token;
}
@@ -31,10 +47,15 @@ public class SimApiAuth(IDistributedCache cache)
/// <returns></returns>
public string Update(SimApiLoginItem loginItem, string token)
{
cache.SetString(token, JsonSerializer.Serialize(loginItem));
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.SetString(cacheKey, SimApiUtil.Json(loginItem));
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.KeyExpire(setCacheKey, ttl);
return token;
}
/// <summary>
/// 获取登陆信息
/// </summary>
@@ -42,19 +63,82 @@ public class SimApiAuth(IDistributedCache cache)
/// <returns></returns>
public SimApiLoginItem? GetLogin(string token)
{
var login = cache.GetString(token);
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : null;
var cacheKey = TokenCacheKey.Replace("{token}", token);
var login = cache.GetString(cacheKey);
var resp = login != null ? SimApiUtil.FromJson<SimApiLoginItem>(login) : null;
if (resp != null)
{
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", resp.Id);
_redisDb.KeyExpire(setCacheKey, ttl);
}
return resp;
}
/// <summary>
/// 获取所有的登录token
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public SimApiLoginItem[] GetAllLogins(string userId)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
var resp = new List<SimApiLoginItem>();
foreach (var login in allLogins)
{
if (login != null)
{
var item = GetLogin(login);
if (item != null)
{
resp.Add(item);
}
else
{
_redisDb.SetRemove(setCacheKey, login);
}
}
}
return resp.ToArray();
}
/// <summary>
/// 退出所有登录
/// </summary>
/// <param name="userId"></param>
public void LogoutAll(string userId)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
foreach (var login in allLogins)
{
if (login != null)
{
var cacheKey = TokenCacheKey.Replace("{token}", login);
cache.Remove(cacheKey);
}
}
_redisDb.KeyDelete(setCacheKey);
}
/// <summary>
/// 退出登陆
/// </summary>
/// <param name="uuid">登陆标识</param>
public void Logout(string uuid)
/// <param name="token">登陆标识</param>
public void Logout(string token)
{
if (!string.IsNullOrEmpty(uuid))
var item = GetLogin(token);
if (item != null)
{
cache.Remove(uuid);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", item.Id);
_redisDb.SetRemove(setCacheKey, token);
}
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.Remove(cacheKey);
}
}
+35 -3
View File
@@ -7,8 +7,15 @@ public class SimApiCache(IDistributedCache cache)
{
private const string Prefix = "SimApi:Cache:";
/// <summary>
/// 设置缓存 (值不能为null)
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
{
SimApiError.ErrorWhenNull(value, 400, "缓存值不能为null");
if (options is not null)
{
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
@@ -19,19 +26,44 @@ public class SimApiCache(IDistributedCache cache)
}
}
/// <summary>
/// 移除缓存
/// </summary>
/// <param name="key"></param>
public void Remove(string key)
{
cache.Remove(Prefix + key);
}
public string? Get(string key)
/// <summary>
/// 缓存Key是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool HasKey(string key)
{
return cache.GetString(Prefix + key);
return Get<string>(key) != null;
}
/// <summary>
/// 获取string类型缓存
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string? Get(string key)
{
return Get<string>(Prefix + key);
}
/// <summary>
/// 获取特定类型缓存
/// </summary>
/// <param name="key"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T? Get<T>(string key)
{
var data = cache.GetString(Prefix + key);
return data == null ? default : JsonSerializer.Deserialize<T>(data);
return data == null ? default : SimApiUtil.FromJson<T>(data);
}
}
+72
View File
@@ -0,0 +1,72 @@
using System.Diagnostics.CodeAnalysis;
using SimApi.Exceptions;
namespace SimApi.Helpers;
public static class SimApiError
{
/// <summary>
/// 错误返回
/// </summary>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
/// <returns></returns>
[DoesNotReturn]
public static void Error(int code = 500, string message = "")
{
throw new SimApiException(code, message);
}
/// <summary>
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
public static void ErrorWhen([DoesNotReturnIf(true)] bool condition, int code = 400,
string message = "")
{
if (condition)
{
Error(code, message);
}
}
/// <summary>
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
public static void ErrorWhenTrue([DoesNotReturnIf(true)] bool condition, int code = 400,
string message = "")
{
ErrorWhen(condition, code, message);
}
/// <summary>
/// 如果condition是false 报错
/// </summary>
/// <param name="condition"></param>
/// <param name="code"></param>
/// <param name="message"></param>
public static void ErrorWhenFalse([DoesNotReturnIf(false)] bool condition, int code = 400,
string message = "")
{
ErrorWhen(!condition, code, message);
}
/// <summary>
/// 检测给定的变量是否为NUll
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
public static void ErrorWhenNull([NotNull] object? condition, int code = 404,
string message = "请求的资源不存在")
{
ErrorWhen(condition == null, code, message);
}
}
+53 -28
View File
@@ -3,20 +3,33 @@ using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using Microsoft.Extensions.Logging;
using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Exceptions;
namespace SimApi.Helpers;
public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHttpClient>? logger = null)
{
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 virtual string Server { get; init; } = apiOptions?.SimApiHttpClientOptions.Server ?? string.Empty;
public virtual string AppId { get; init; } = apiOptions?.SimApiHttpClientOptions.AppId ?? string.Empty;
public virtual string AppKey { get; init; } = apiOptions?.SimApiHttpClientOptions.AppKey ?? string.Empty;
public virtual string SignName { get; init; } = "sign";
public virtual string TimestampName { get; init; } = "timestamp";
public virtual string NonceName { get; init; } = "nonce";
public virtual string? AppIdName { get; init; } = "appId";
public virtual string[] SignFields { get; init; } = [];
/// <summary>
/// 发起签名请求
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <param name="queries"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
{
url = Server + url;
@@ -24,11 +37,11 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
(current, signField) => current + $"{signField}={queries?[signField]}&");
if (!string.IsNullOrEmpty(AppIdName))
{
queryUrl += $"{AppIdName}={appId}&";
queryUrl += $"{AppIdName}={AppId}&";
}
queryUrl += $"{TimestampName}={(int)SimApiUtil.TimestampNow}&{NonceName}={Guid.NewGuid()}";
var signStr = $"{queryUrl}&{appKey}";
var signStr = $"{queryUrl}&{AppKey}";
var path = $"{url}?{queryUrl}&{SignName}={SimApiUtil.Md5(signStr)}";
if (queries != null)
@@ -40,50 +53,62 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
return Query<T>(path, body);
}
/// <summary>
/// 发起AES加密请求
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T? AesQuery<T>(string url, object body)
{
url = Server + url;
if (!string.IsNullOrEmpty(AppIdName))
{
url += $"?{AppIdName}={appId}";
url += $"?{AppIdName}={AppId}";
}
var req = new SimApiOneFieldRequest<string>
{
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
};
return Query<T>(url, req);
}
/// <summary>
/// 发起AES加密以及签名请求
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <param name="queries"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
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)
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
};
return SignQuery<T>(url, req, queries);
}
/// <summary>
/// 发起请求
/// </summary>
/// <param name="url"></param>
/// <param name="req"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="SimApiException"></exception>
private T? Query<T>(string url, object? req)
{
var http = new HttpClient();
if (debug)
{
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
}
logger?.LogDebug($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
var resp = http.PostAsJsonAsync(url, req).Result;
if (debug)
{
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
}
logger?.LogDebug($"[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;
SimApiError.ErrorWhenNull(res, 500, "请求发生错误");
SimApiError.ErrorWhen(res.Code != 200, res.Code, res.Message);
return res.Data;
}
}
+76
View File
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
@@ -94,6 +95,25 @@ public static class SimApiUtil
return regex.IsMatch(cell);
}
/// <summary>
/// 判断是否是Email地址
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static bool CheckEmail(string email)
{
try
{
var m = new MailAddress(email);
return m.Address == email;
}
catch
{
return false;
}
}
/// <summary>
/// MD5加密字符串
/// </summary>
@@ -131,6 +151,51 @@ public static class SimApiUtil
return sb.ToString();
}
/// <summary>
/// 字符串Base64编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Encode(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// 从Base64中解码字符串
/// </summary>
/// <param name="base64Str"></param>
/// <returns></returns>
public static string Base64Decode(string base64Str)
{
var bytes = Convert.FromBase64String(base64Str);
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// 把对象Base64编码
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string Base64Encode(object obj)
{
var json = Json(obj);
return Base64Encode(json);
}
/// <summary>
/// 从Base64中解析对象
/// </summary>
/// <param name="base64Str"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T? Base64Decode<T>(string base64Str)
{
var json = Base64Decode(base64Str);
return FromJson<T>(json);
}
/// <summary>
/// 将XML字符串序列化为对象
/// </summary>
@@ -154,6 +219,17 @@ public static class SimApiUtil
return JsonSerializer.Serialize(obj, JsonOption);
}
/// <summary>
/// 将JSON解析为对象(控制台输出中文不会被编码)
/// </summary>
/// <param name="jsonString"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T? FromJson<T>(string jsonString)
{
return JsonSerializer.Deserialize<T>(jsonString, JsonOption);
}
/// <summary>
/// 分页
/// </summary>
+8
View File
@@ -0,0 +1,8 @@
using SimApi.Communications;
namespace SimApi.Interfaces;
public interface ISimApiAuthChecker
{
public void Run(SimApiLoginItem loginItem, string token);
}
+7 -9
View File
@@ -1,8 +1,6 @@
using System.Text.Json;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.Middlewares;
@@ -12,20 +10,20 @@ namespace SimApi.Middlewares;
/// </summary>
public class SimApiAuthMiddleware(RequestDelegate next)
{
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
public Task Invoke(HttpContext httpContext, SimApiAuth auth)
{
string? token = null;
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
{
token = header;
}
var token =
httpContext.Request.Headers["Token"].FirstOrDefault()
?? httpContext.Request.Query["token"].FirstOrDefault();
if (string.IsNullOrEmpty(token)) return next(httpContext);
var login = auth.GetLogin(token);
if (login != null)
{
httpContext.Items.Add("LoginToken", token);
httpContext.Items.Add("LoginInfo", login);
}
return next(httpContext);
}
}
+11 -12
View File
@@ -1,16 +1,22 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SimApi.Communications;
using Microsoft.Extensions.Logging;
using SimApi.Configurations;
using SimApi.Exceptions;
using SimApi.Helpers;
namespace SimApi.Middlewares;
/// <summary>
/// 异常处理中间件
/// </summary>
public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExceptionMiddleware> log)
public class SimApiExceptionMiddleware(
RequestDelegate next,
ILogger<SimApiExceptionMiddleware> log,
SimApiOptions simApiOptions)
{
public async Task InvokeAsync(HttpContext context)
{
@@ -24,17 +30,9 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
await next(context);
if (!context.Response.HasStarted)
{
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);
}
SimApiError.ErrorWhenFalse(
simApiOptions.SimApiExceptionOptions.SkipStatusCodes.Contains(context.Response.StatusCode),
context.Response.StatusCode);
}
}
catch (Exception ex)
@@ -79,6 +77,7 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
context.Response.ContentLength = null; // 清除可能已设置的 Content-Length
await context.Response.WriteAsync(response.ToString());
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ public class AesBodyModelBinder : IModelBinder
SimApiOneFieldRequest<string>? aesRequest;
try
{
aesRequest = JsonSerializer.Deserialize<SimApiOneFieldRequest<string>>(requestBody, SimApiUtil.JsonOption);
aesRequest = SimApiUtil.FromJson<SimApiOneFieldRequest<string>>(requestBody);
}
catch (JsonException ex)
{
+934 -715
View File
File diff suppressed because it is too large Load Diff
+61 -53
View File
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
@@ -17,10 +16,12 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SimApi.Attributes;
using SimApi.CoceSdk;
using SimApi.AuthGate;
using SimApi.Configurations;
using SimApi.Interfaces;
using SimApi.Logger;
using SimApi.SwaggerFilters;
using StackExchange.Redis;
namespace SimApi;
@@ -38,6 +39,8 @@ public static class SimApiExtensions
if (simApiOptions.RedisConfiguration != null)
{
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
builder.AddSingleton<IConnectionMultiplexer>(_ =>
ConnectionMultiplexer.Connect(simApiOptions.RedisConfiguration));
builder.AddSingleton<SimApiCache>();
}
@@ -56,9 +59,18 @@ public static class SimApiExtensions
builder.AddSingleton<SimApiAuth>();
}
if (simApiOptions.EnableCoceSdk)
var simApiAuthChecker = typeof(ISimApiAuthChecker);
var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var callerAssembly = callingMethod?.DeclaringType?.Assembly;
var callerTypes = callerAssembly?.GetTypes() ?? [];
foreach (var type in callerTypes)
{
builder.AddSingleton<CoceApp>();
if (type is { IsClass: true, IsAbstract: false } && simApiAuthChecker.IsAssignableFrom(type))
{
builder.AddScoped(simApiAuthChecker, type);
}
}
if (simApiOptions.EnableJob)
@@ -91,15 +103,15 @@ public static class SimApiExtensions
policy => { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));
}
if (simApiOptions.EnableSimApiHttpClient)
{
builder.AddSingleton<SimApiHttpClient>();
}
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)
foreach (var type in callerTypes)
{
var methodsWithSynapse = type.GetMethods()
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
@@ -136,14 +148,14 @@ public static class SimApiExtensions
if (t.IsArray)
{
var elementType = t.GetElementType();
return $"{GetSimpleTypeName(elementType, depth + 1)}[]";
return $"{GetSimpleTypeName(elementType!, depth + 1)}[]";
}
// 处理可空类型
if (Nullable.GetUnderlyingType(t) != null)
{
var underlyingType = Nullable.GetUnderlyingType(t);
return GetSimpleTypeName(underlyingType, depth + 1);
return GetSimpleTypeName(underlyingType!, depth + 1);
}
// 处理泛型类型(递归解析嵌套泛型)
@@ -317,6 +329,13 @@ public static class SimApiExtensions
});
}
if (simApiOptions.EnableSimApiAuthGate)
{
builder.AddSingleton<SimApiAuthGateClient>();
builder.AddSingleton<SimApiAuthGate>();
builder.AddSingleton<SimApiIam>();
}
builder.AddSingleton(simApiOptions);
return builder;
}
@@ -343,11 +362,11 @@ public static class SimApiExtensions
builder.Services.GetService<SimApiStorage>();
}
if (options.EnableCoceSdk)
if (options.EnableSimApiHttpClient)
{
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
options.CoceSdkOptions.AppId);
logger.LogInformation("开始配置SimApiHttpClient...\n服务器地址: {ApiUrl}\nAppId:{AuthUrl}n\nAppkey: {AppId}",
options.SimApiHttpClientOptions.Server, options.SimApiHttpClientOptions.AppId,
!string.IsNullOrEmpty(options.SimApiHttpClientOptions.AppKey));
}
if (options.EnableSynapse)
@@ -392,52 +411,41 @@ public static class SimApiExtensions
builder.MapControllers();
}
var checkers = builder.Services.CreateScope().ServiceProvider.GetServices<ISimApiAuthChecker>().ToArray();
if (checkers.Length != 0)
{
var msg = checkers.Aggregate("开始配置SimApiAuthChecker...",
(current, checker) => current + $"\n|- {checker.GetType().FullName}");
logger.LogInformation(msg);
}
if (options.EnableSimApiAuthGate)
{
logger.LogInformation("开始配置SimApiAuthGate...");
if (string.IsNullOrEmpty(options.SimApiAuthGateOptions.AppId) ||
string.IsNullOrEmpty(options.SimApiAuthGateOptions.AppKey))
{
logger.LogCritical("必须配置AuthGate的AppId和AppKey才能启用SimApiAuthGate");
}
else
{
if (options.SimApiAuthGateOptions.UseMiddleware)
{
builder.UseMiddleware<SimApiAuthGateMiddleware>();
}
}
}
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)
@@ -460,7 +468,7 @@ public static class SimApiExtensions
x.DocumentTitle = docOptions.DocumentTitle;
foreach (var group in docOptions.ApiGroups)
{
x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name);
x.SwaggerEndpoint($"{group.Id}.json", name: group.Name);
}
x.SupportedSubmitMethods(docOptions.SupportedMethod);
+2 -2
View File
@@ -22,11 +22,11 @@ public class AesBodyOperationFilter : IOperationFilter
.GetCustomAttribute<AesBodyAttribute>() != null;
if (!hasAesBodyAttr) continue;
// 1. 移除默认的 Query 参数描述(如果存在)
var queryParam = operation.Parameters
var queryParam = operation.Parameters!
.FirstOrDefault(p => p.Name == parameter.Name);
if (queryParam != null)
{
operation.Parameters.Remove(queryParam);
operation.Parameters!.Remove(queryParam);
}
// 2. 添加 Body 参数描述
@@ -13,7 +13,7 @@ public class GlobalDynamicObjectSchemaFilter : ISchemaFilter
{
if (!IsDynamicObjectType(context.Type)) return;
var oaSchema = schema as OpenApiSchema;
oaSchema.AdditionalPropertiesAllowed = true;
oaSchema!.AdditionalPropertiesAllowed = true;
oaSchema.AdditionalProperties = new OpenApiSchema
{
Type = JsonSchemaType.Object, // 表示 value 可以是任意类型(兼容所有类型)
+4 -4
View File
@@ -10,16 +10,16 @@ public class RemoveEmptyTagsFilter : IDocumentFilter
{
// 步骤1:收集所有有接口的 Tag 名称
var tagsWithOperations = swaggerDoc.Paths.Values
.SelectMany(path => path.Operations.Values)
.SelectMany(op => op.Tags.Select(t => t.Name))
.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();
var emptyTags = swaggerDoc.Tags!.Where(t => !tagsWithOperations.Contains(t.Name)).ToList();
foreach (var tag in emptyTags)
{
swaggerDoc.Tags.Remove(tag);
swaggerDoc.Tags!.Remove(tag);
}
}
}
@@ -46,7 +46,7 @@ public class SimApiResponseOperationFilter : IOperationFilter
var schema = context.SchemaGenerator.GenerateSchema(wrappedType, context.SchemaRepository);
// 5. 替换 Swagger 文档中的响应类型(只保留 200 OK 的响应,匹配过滤器逻辑)
operation.Responses.Clear(); // 清除默认响应(如 200 返回原始类型)
operation.Responses!.Clear(); // 清除默认响应(如 200 返回原始类型)
operation.Responses.Add("200", new OpenApiResponse
{
Description = "请求成功",
+2 -1
View File
@@ -17,8 +17,9 @@ public partial class Synapse
}
else
{
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
paramJson = SimApiUtil.Json(param);
}
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
+4 -5
View File
@@ -50,7 +50,7 @@ public partial class Synapse
}
else
{
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
paramJson = SimApiUtil.Json(param);
}
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
@@ -73,7 +73,7 @@ public partial class Synapse
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));
messageId, Options.AppName, action, app, paramJson, SimApiUtil.Json(headers));
string response;
try
@@ -88,13 +88,12 @@ public partial class Synapse
}
else
{
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
response = SimApiUtil.Json(new SimApiBaseResponse(502, "timeout"));
}
}
catch
{
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"),
SimApiUtil.JsonOption);
response = SimApiUtil.Json(new SimApiBaseResponse(500, "Synapse RPC Client Error"));
}
return response;
+2 -2
View File
@@ -10,7 +10,7 @@ using MQTTnet.Protocol;
using SimApi.Communications;
using SimApi.Exceptions;
using SimApi.Helpers;
using JsonSerializer = System.Text.Json.JsonSerializer;
using System.Text.Json;
namespace SimApi;
@@ -96,7 +96,7 @@ public partial class Synapse
}
}
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
var returnJson = SimApiUtil.Json(res);
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
var message = new MqttApplicationMessageBuilder()
.WithTopic(reply)
+1 -1
View File
@@ -101,7 +101,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
else
{
var data = FireRpc(appName, method, param, headers, timeout);
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
res = SimApiUtil.FromJson<SimApiBaseResponse<T>>(data);
}
return (res as SimApiBaseResponse<T>)!;
-828
View File
@@ -1,828 +0,0 @@
# 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 处理 |