Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebceb0a260 | ||
|
|
162b92a415 | ||
|
|
a859986a93 | ||
|
|
e1c6694e18 | ||
|
|
566b1d190b | ||
|
|
eb8c9732bd | ||
|
|
c8b78ce86d |
+574
@@ -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 => {...})` |
|
||||
|
||||
---
|
||||
|
||||
## SimApiOptions(AddSimApi 配置)
|
||||
|
||||
```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×tamp=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 → 公开访问 URL;r.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(封装响应)
|
||||
```
|
||||
@@ -12,12 +12,12 @@ public class SimApiDocAttribute : SwaggerOperationAttribute
|
||||
/// <summary>
|
||||
/// 定义接口说明
|
||||
/// </summary>
|
||||
/// <param name="tag">接口分组</param>
|
||||
/// <param name="tags">接口分组列表</param>
|
||||
/// <param name="name">接口名称</param>
|
||||
/// <param name="description">接口描述</param>
|
||||
public SimApiDocAttribute(string tag, string name, string? description = null)
|
||||
public SimApiDocAttribute(string[] tags, string name, string? description = null)
|
||||
{
|
||||
Tags = [tag];
|
||||
Tags = tags;
|
||||
Summary = name;
|
||||
if (description != null)
|
||||
{
|
||||
@@ -26,4 +26,14 @@ public class SimApiDocAttribute : SwaggerOperationAttribute
|
||||
// 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)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -29,11 +29,12 @@ public class SimApiJobOptions
|
||||
/// 设置为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; } = 50;
|
||||
public int WorkerNum { get; set; } = 5;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SimApi.Attributes;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Helpers;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Communications;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
@@ -38,74 +37,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>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
global using static SimApiErrorExtension;
|
||||
@@ -19,6 +19,11 @@ public class SimApiCache(IDistributedCache cache)
|
||||
}
|
||||
}
|
||||
|
||||
public void Remove(string key)
|
||||
{
|
||||
cache.Remove(Prefix + key);
|
||||
}
|
||||
|
||||
public string? Get(string key)
|
||||
{
|
||||
return cache.GetString(Prefix + key);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using SimApi.Communications;
|
||||
@@ -20,7 +19,6 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
||||
context.Response.Headers["Query-Id"] = header;
|
||||
}
|
||||
|
||||
SimApiBaseResponse response;
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
@@ -39,31 +37,48 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
{
|
||||
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()).Wait();
|
||||
context.Response.ContentType = "application/json";
|
||||
await context.Response.WriteAsync(response.ToString());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<PackOnBuild>true</PackOnBuild>
|
||||
@@ -12,10 +11,6 @@
|
||||
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="Communications\"/>
|
||||
<Folder Include="Exceptions\"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
|
||||
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
|
||||
@@ -26,16 +21,4 @@
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include=".github\workflows\nuget-publish.yml" />
|
||||
</ItemGroup>
|
||||
<ProjectExtensions>
|
||||
<MonoDevelop>
|
||||
<Properties>
|
||||
<Policies>
|
||||
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical"/>
|
||||
</Policies>
|
||||
</Properties>
|
||||
</MonoDevelop>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using SimApi.Exceptions;
|
||||
|
||||
|
||||
public static class SimApiErrorExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 错误返回
|
||||
/// </summary>
|
||||
/// <param name="code">错误代码</param>
|
||||
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
|
||||
/// <returns></returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
@@ -136,14 +135,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);
|
||||
}
|
||||
|
||||
// 处理泛型类型(递归解析嵌套泛型)
|
||||
|
||||
-796
@@ -1,796 +0,0 @@
|
||||
# SimApi 库使用说明书
|
||||
|
||||
## 1. 项目概述
|
||||
|
||||
SimApi 是一个基于 .NET 的基础辅助包,提供了一系列实用功能,帮助开发者快速构建和部署 API 服务。
|
||||
|
||||
### 主要功能特性:
|
||||
|
||||
- **统一的参数检测和错误处理**:自动验证请求参数并返回标准化的错误响应
|
||||
- **基础认证服务**:基于 Header Token 的简单认证机制
|
||||
- **S3 兼容的存储系统**:支持文件上传、下载和管理
|
||||
- **任务调度系统**:基于 Hangfire 的后台任务管理
|
||||
- **事件和 RPC 调用**:基于 RabbitMQ 的事件和 RPC 通信
|
||||
- **自定义日志格式**:提供格式化的控制台日志
|
||||
- **在线 API 文档**:基于 Swagger 的 API 文档生成
|
||||
- **统一的响应格式**:标准化的 API 响应结构
|
||||
- **CORS 配置**:支持跨域资源共享
|
||||
- **版本管理**:提供应用版本和 SimApi 版本查询
|
||||
|
||||
## 2. 安装方法
|
||||
|
||||
### 通过 NuGet 安装:
|
||||
|
||||
```bash
|
||||
Install-Package SimApi
|
||||
```
|
||||
|
||||
### 项目集成
|
||||
|
||||
在 `Startup.cs` 或 `Program.cs` 中配置 SimApi:
|
||||
|
||||
```csharp
|
||||
// 在 ConfigureServices 方法中
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
// 配置选项
|
||||
});
|
||||
|
||||
// 在 Configure 方法中
|
||||
app.UseSimApi();
|
||||
```
|
||||
|
||||
## 3. 核心功能模块
|
||||
|
||||
### 3.1 基础控制器
|
||||
|
||||
所有控制器应继承自 `SimApiBaseController`,以获得统一的参数检测和错误处理功能。
|
||||
|
||||
```csharp
|
||||
using SimApi.Controllers;
|
||||
|
||||
public class BaseController : SimApiBaseController
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取登录用户信息
|
||||
/// </summary>
|
||||
protected SimApiLoginItem LoginInfo => (SimApiLoginItem) HttpContext.Items["LoginInfo"];
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 认证服务
|
||||
|
||||
#### 配置认证服务:
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
options.EnableSimApiAuth = true;
|
||||
});
|
||||
```
|
||||
|
||||
#### 使用认证:
|
||||
|
||||
1. 在控制器或动作方法上添加 `[SimApiAuth]` 属性
|
||||
2. 登录用户信息可通过 `LoginInfo` 属性获取
|
||||
|
||||
#### 认证相关接口:
|
||||
|
||||
- `POST /auth/check`:检测用户登录状态
|
||||
- `POST /auth/logout`:用户退出登录
|
||||
- `POST /user/info`:获取用户信息
|
||||
|
||||
### 3.3 存储服务
|
||||
|
||||
#### 配置存储服务:
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
options.EnableSimApiStorage = true;
|
||||
options.SimApiStorageOptions = Configuration.GetSection("S3").Get<SimApiStorageOptions>();
|
||||
});
|
||||
```
|
||||
|
||||
#### 存储配置选项:
|
||||
|
||||
```json
|
||||
{
|
||||
"S3": {
|
||||
"Endpoint": "http://localhost:9000",
|
||||
"AccessKey": "minioadmin",
|
||||
"SecretKey": "minioadmin",
|
||||
"Bucket": "mybucket",
|
||||
"ServeUrl": "http://localhost:9000/mybucket"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 使用存储服务:
|
||||
|
||||
```csharp
|
||||
private readonly SimApiStorage _storage;
|
||||
|
||||
public MyController(SimApiStorage storage)
|
||||
{
|
||||
_storage = storage;
|
||||
}
|
||||
|
||||
// 获取上传 URL
|
||||
var uploadUrlResponse = _storage.GetUploadUrl("/path/to/file.txt");
|
||||
|
||||
// 获取下载 URL
|
||||
var downloadUrl = _storage.GetDownloadUrl("/path/to/file.txt");
|
||||
|
||||
// 直接上传文件
|
||||
using var stream = new MemoryStream();
|
||||
_storage.UploadFile("/path/to/file.txt", stream, "text/plain");
|
||||
|
||||
// 获取完整访问 URL
|
||||
var fullUrl = _storage.FullUrl("/path/to/file.txt");
|
||||
```
|
||||
|
||||
### 3.4 任务调度系统
|
||||
|
||||
#### 配置任务调度:
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
options.EnableJob = true;
|
||||
options.SimApiJobOptions = new SimApiJobOptions
|
||||
{
|
||||
DashboardUrl = "/jobs",
|
||||
DashboardAuthUser = "admin",
|
||||
DashboardAuthPass = "Admin@123!",
|
||||
RedisConfiguration = "localhost:6379",
|
||||
Servers = new[]
|
||||
{
|
||||
new SimApiJobServerConfig
|
||||
{
|
||||
Queues = new[] { "default" },
|
||||
WorkerNum = 50
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
#### 使用任务调度:
|
||||
|
||||
```csharp
|
||||
// 立即执行任务
|
||||
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
|
||||
|
||||
// 延迟执行任务
|
||||
BackgroundJob.Schedule(() => Console.WriteLine("Delayed job"), TimeSpan.FromMinutes(1));
|
||||
|
||||
// 重复执行任务
|
||||
RecurringJob.AddOrUpdate("my-recurring-job", () => Console.WriteLine("Recurring job"), Cron.Hourly);
|
||||
|
||||
// 连续执行任务
|
||||
var id = BackgroundJob.Enqueue(() => Console.WriteLine("First job"));
|
||||
BackgroundJob.ContinueWith(id, () => Console.WriteLine("Second job"));
|
||||
```
|
||||
|
||||
### 3.5 事件和 RPC 调用
|
||||
|
||||
#### 配置事件和 RPC:
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
options.EnableSynapse = true;
|
||||
options.SimApiSynapseOptions = new SimApiSynapseOptions
|
||||
{
|
||||
// 配置选项
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
#### 使用事件:
|
||||
|
||||
```csharp
|
||||
// 发布事件
|
||||
var synapse = serviceProvider.GetRequiredService<Synapse>();
|
||||
synapse.PublishEvent("event-name", data);
|
||||
|
||||
// 订阅事件
|
||||
[SynapseEvent("event-name")]
|
||||
public void HandleEvent(dynamic data)
|
||||
{
|
||||
// 处理事件
|
||||
}
|
||||
```
|
||||
|
||||
#### 使用 RPC:
|
||||
|
||||
```csharp
|
||||
// 发布 RPC 调用
|
||||
var result = await synapse.CallRpcAsync<string>("rpc-method", data);
|
||||
|
||||
// 实现 RPC 方法
|
||||
[SynapseRpc("rpc-method")]
|
||||
public string GetData(dynamic data)
|
||||
{
|
||||
return "Hello, RPC!";
|
||||
}
|
||||
```
|
||||
|
||||
### 3.6 在线 API 文档
|
||||
|
||||
#### 配置 API 文档:
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
options.EnableSimApiDoc = true;
|
||||
options.ConfigureSimApiDoc(docOptions =>
|
||||
{
|
||||
docOptions.ApiGroups = new[]
|
||||
{
|
||||
new SimApiDocGroupOption
|
||||
{
|
||||
Id = "admin",
|
||||
Name = "后台管理接口",
|
||||
Description = "本接口调用需要Scope:sac.api.admin"
|
||||
},
|
||||
new SimApiDocGroupOption
|
||||
{
|
||||
Id = "user-v1",
|
||||
Name = "用户中心接口",
|
||||
Description = "本接口调用需要Scope:sac.api.user"
|
||||
}
|
||||
};
|
||||
docOptions.ApiAuth = new SimApiAuthOption
|
||||
{
|
||||
Type = new[] { "ClientCredentials", "Implicit", "AuthorizationCode" },
|
||||
Scopes = new Dictionary<string, string>
|
||||
{
|
||||
{ "sac.api.user", "用户信息接口权限" },
|
||||
{ "sac.api.admin", "后台管理API" }
|
||||
},
|
||||
AuthorizationUrl = "/connect/authorize",
|
||||
TokenUrl = "/connect/token"
|
||||
};
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
#### 访问 API 文档:
|
||||
|
||||
启动应用后,访问 `/swagger` 查看 API 文档。
|
||||
|
||||
### 3.7 统一响应格式
|
||||
|
||||
#### 配置响应过滤器:
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
options.EnableSimApiResponseFilter = true;
|
||||
});
|
||||
```
|
||||
|
||||
#### 响应过滤器实现:
|
||||
|
||||
SimApi 提供了 `SimApiResponseFilter` 结果过滤器,用于自动封装 API 响应为统一格式:
|
||||
|
||||
- 自动将 `null` 结果封装为 `{"Code": 200, "Message": "成功"}`
|
||||
- 自动将普通对象结果封装为 `{"Code": 200, "Message": "成功", "Data": 对象}`
|
||||
- 自动将 `EmptyResult` 封装为 `{"Code": 200, "Message": "成功"}`
|
||||
- 保持 `SimApiBaseResponse` 类型的结果不变
|
||||
|
||||
#### 异常中间件:
|
||||
|
||||
SimApi 还提供了 `SimApiExceptionMiddleware` 异常中间件,用于统一处理异常:
|
||||
|
||||
- 捕获所有未处理的异常
|
||||
- 将异常转换为标准化的错误响应格式
|
||||
- 处理 HTTP 状态码,如 404 等
|
||||
- 记录错误日志
|
||||
|
||||
#### 使用响应格式:
|
||||
|
||||
```csharp
|
||||
// 无数据响应
|
||||
return new SimApiBaseResponse();
|
||||
|
||||
// 带数据响应
|
||||
return new SimApiBaseResponse<User>(user);
|
||||
|
||||
// 直接返回对象,会自动被封装
|
||||
return user;
|
||||
|
||||
// 错误响应
|
||||
Error(400, "参数错误");
|
||||
|
||||
// 条件错误检查
|
||||
ErrorWhenNull(user, 404, "用户不存在");
|
||||
ErrorWhen(user.Age < 18, 403, "未满18岁,无权访问");
|
||||
```
|
||||
|
||||
#### 原始响应标记:
|
||||
|
||||
如果需要返回原始响应格式,不使用统一封装,可以在控制器或动作方法上添加 `[OriginResponse]` 属性:
|
||||
|
||||
```csharp
|
||||
[HttpGet]
|
||||
[OriginResponse] // 返回原始响应格式
|
||||
public string GetRawData()
|
||||
{
|
||||
return "原始字符串响应";
|
||||
}
|
||||
```
|
||||
|
||||
## 4. API 参考
|
||||
|
||||
### 4.1 核心类
|
||||
|
||||
#### SimApiUtil
|
||||
|
||||
**命名空间**:`SimApi.Helpers`
|
||||
|
||||
**描述**:提供一系列静态工具方法和属性,用于常见操作。
|
||||
|
||||
**主要属性**:
|
||||
|
||||
- `CstNow`:获取当前 CST(中国标准时间)
|
||||
- `JsonOption`:JSON 序列化常规选项
|
||||
- `SimApiVersion`:获取 SimApi 库版本
|
||||
- `AppVersion`:获取应用版本
|
||||
- `TimestampNow`:获取当前秒级时间戳
|
||||
|
||||
**主要方法**:
|
||||
|
||||
- `CheckCell(string cell)`:检测手机号是否正确
|
||||
- `Md5(string source, string mode = "x2")`:MD5 加密字符串
|
||||
- `Sha1(string source, string mode = "x2")`:SHA1 加密字符串
|
||||
- `XmlDeserialize<T>(string source)`:将 XML 字符串序列化为对象
|
||||
- `Json(object? obj)`:将对象序列化为 JSON 字符串
|
||||
- `Paginate<T>(this IQueryable<T> query, int page, int count)`:分页扩展方法
|
||||
|
||||
**使用示例**:
|
||||
|
||||
```csharp
|
||||
// 获取当前时间
|
||||
var now = SimApiUtil.CstNow;
|
||||
|
||||
// JSON 序列化
|
||||
var json = SimApiUtil.Json(new { Name = "Test", Age = 18 });
|
||||
|
||||
// MD5 加密
|
||||
var md5 = SimApiUtil.Md5("password");
|
||||
|
||||
// 分页
|
||||
var query = dbContext.Users.AsQueryable();
|
||||
var paginatedQuery = query.Paginate(1, 10);
|
||||
|
||||
// 获取版本信息
|
||||
var simApiVersion = SimApiUtil.SimApiVersion;
|
||||
var appVersion = SimApiUtil.AppVersion;
|
||||
```
|
||||
|
||||
#### SimApiExtensions
|
||||
|
||||
**命名空间**:`SimApi`
|
||||
|
||||
**描述**:提供一系列扩展方法,用于配置和使用 SimApi。
|
||||
|
||||
**主要方法**:
|
||||
|
||||
- `AddSimApi(this IServiceCollection builder, Action<SimApiOptions>? options = null)`:向服务集合添加 SimApi 服务和配置
|
||||
- `UseSimApi(this IHost builder)`:在主机上使用 SimApi
|
||||
- `UseSimApi(this WebApplication builder)`:在 Web 应用上使用 SimApi,配置中间件和路由
|
||||
|
||||
**使用示例**:
|
||||
|
||||
```csharp
|
||||
// 在 ConfigureServices 方法中
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
// 配置选项
|
||||
options.EnableSimApiDoc = true;
|
||||
options.EnableSimApiAuth = true;
|
||||
// 其他配置...
|
||||
});
|
||||
|
||||
// 在 Configure 方法中
|
||||
app.UseSimApi();
|
||||
```
|
||||
|
||||
#### SimApiBaseController
|
||||
|
||||
**继承自**:`Controller`
|
||||
|
||||
**主要方法**:
|
||||
|
||||
- `Error(int code = 500, string message = "")`:抛出错误异常
|
||||
- `ErrorWhen(bool condition, int code = 400, string message = "")`:当条件为真时抛出错误
|
||||
- `ErrorWhenNull(object? condition, int code = 404, string message = "请求的资源不存在")`:当对象为 null 时抛出错误
|
||||
- `UploadFile()`:上传文件
|
||||
|
||||
**属性**:
|
||||
|
||||
- `LoginInfo`:获取当前登录用户信息
|
||||
|
||||
#### SimApiAuth
|
||||
|
||||
**主要方法**:
|
||||
|
||||
- `Login(SimApiLoginItem loginItem, string? token = null)`:登录用户并返回 token
|
||||
- `Update(SimApiLoginItem loginItem, string token)`:更新用户登录信息
|
||||
- `GetLogin(string token)`:根据 token 获取登录信息
|
||||
- `Logout(string uuid)`:退出登录
|
||||
|
||||
#### SimApiStorage
|
||||
|
||||
**主要方法**:
|
||||
|
||||
- `GetUploadUrl(string path, int expire = 7200)`:获取文件上传 URL
|
||||
- `GetDownloadUrl(string path, int expire = 600)`:获取文件下载 URL
|
||||
- `UploadFile(string path, Stream stream, string contentType = "image/png")`:上传文件
|
||||
- `FullUrl(string? path)`:获取完整的文件访问 URL
|
||||
- `GetUrl(string? path)`:获取文件访问 URL
|
||||
- `GetPath(string? url)`:从 URL 中获取相对路径
|
||||
|
||||
#### SimApiBaseResponse
|
||||
|
||||
**构造函数**:
|
||||
|
||||
- `SimApiBaseResponse(int code = 200, string message = "成功")`:创建响应对象
|
||||
|
||||
**属性**:
|
||||
|
||||
- `Code`:响应代码
|
||||
- `Message`:响应消息
|
||||
|
||||
#### SimApiBaseResponse<T>
|
||||
|
||||
**继承自**:`SimApiBaseResponse`
|
||||
|
||||
**构造函数**:
|
||||
|
||||
- `SimApiBaseResponse(T data)`:创建带数据的响应对象
|
||||
|
||||
**属性**:
|
||||
|
||||
- `Data`:响应数据
|
||||
|
||||
### 4.2 配置类
|
||||
|
||||
#### SimApiOptions
|
||||
|
||||
**主要属性**:
|
||||
|
||||
- `RedisConfiguration`:Redis 配置字符串
|
||||
- `EnableJob`:是否启用任务调度系统
|
||||
- `EnableSimApiAuth`:是否启用认证服务
|
||||
- `EnableCoceSdk`:是否启用 CoceSdk
|
||||
- `EnableSimApiStorage`:是否启用存储服务
|
||||
- `EnableSimApiDoc`:是否启用 API 文档
|
||||
- `EnableSynapse`:是否启用事件和 RPC
|
||||
- `EnableCors`:是否启用 CORS
|
||||
- `EnableSimApiException`:是否启用异常拦截
|
||||
- `EnableSimApiResponseFilter`:是否启用响应过滤器
|
||||
- `EnableForwardHeaders`:是否启用 Header 转发
|
||||
- `EnableLowerUrl`:是否启用小写 URL
|
||||
- `EnableVersionUrl`:是否启用版本查询
|
||||
- `EnableLogger`:是否启用自定义日志
|
||||
|
||||
**配置方法**:
|
||||
|
||||
- `ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)`:配置 API 文档
|
||||
- `ConfigureSimApiStorage(Action<SimApiStorageOptions>? options = null)`:配置存储服务
|
||||
- `ConfigureSimApiJob(Action<SimApiJobOptions>? options = null)`:配置任务调度
|
||||
- `ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)`:配置事件和 RPC
|
||||
- `ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)`:配置 CoceSdk
|
||||
|
||||
## 5. 配置选项
|
||||
|
||||
### 5.1 存储配置 (SimApiStorageOptions)
|
||||
|
||||
```csharp
|
||||
public class SimApiStorageOptions
|
||||
{
|
||||
public string? Endpoint { get; set; } // S3 服务端点
|
||||
public string? AccessKey { get; set; } // 访问密钥
|
||||
public string? SecretKey { get; set; } // 密钥
|
||||
public string? Bucket { get; set; } // 存储桶名称
|
||||
public string? ServeUrl { get; set; } // 访问 URL
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 任务调度配置 (SimApiJobOptions)
|
||||
|
||||
```csharp
|
||||
public class SimApiJobOptions
|
||||
{
|
||||
public string? DashboardUrl { get; set; } = "/jobs"; // Web UI 地址
|
||||
public string DashboardAuthUser { get; set; } = "admin"; // Web UI 用户名
|
||||
public string DashboardAuthPass { get; set; } = "Admin@123!"; // Web UI 密码
|
||||
public string? RedisConfiguration { get; set; } // Redis 配置
|
||||
public int? Database { get; set; } = null; // Redis 数据库
|
||||
public SimApiJobServerConfig[] Servers { get; set; } = [new()]; // 服务器配置
|
||||
}
|
||||
|
||||
public class SimApiJobServerConfig
|
||||
{
|
||||
public string[] Queues { get; set; } = ["default"]; // 队列名称
|
||||
public int WorkerNum { get; set; } = 50; // 工作线程数
|
||||
}
|
||||
```
|
||||
|
||||
### 5.3 API 文档配置 (SimApiDocOptions)
|
||||
|
||||
```csharp
|
||||
public class SimApiDocOptions
|
||||
{
|
||||
public string DocumentTitle { get; set; } = "API 文档"; // 文档标题
|
||||
public SimApiDocGroupOption[] ApiGroups { get; set; } = []; // API 分组
|
||||
public SimApiAuthOption ApiAuth { get; set; } = new(); // 认证配置
|
||||
public string[] SupportedMethod { get; set; } = ["GET", "POST", "PUT", "DELETE"]; // 支持的 HTTP 方法
|
||||
}
|
||||
|
||||
public class SimApiDocGroupOption
|
||||
{
|
||||
public string Id { get; set; } = "api"; // 分组 ID
|
||||
public string Name { get; set; } = "API"; // 分组名称
|
||||
public string Description { get; set; } = ""; // 分组描述
|
||||
}
|
||||
|
||||
public class SimApiAuthOption
|
||||
{
|
||||
public string[] Type { get; set; } = []; // 认证类型
|
||||
public Dictionary<string, string> Scopes { get; set; } = []; // 权限范围
|
||||
public string AuthorizationUrl { get; set; } = "/connect/authorize"; // 授权 URL
|
||||
public string TokenUrl { get; set; } = "/connect/token"; // Token URL
|
||||
public string Description { get; set; } = ""; // 认证描述
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 使用示例
|
||||
|
||||
### 6.1 完整配置示例
|
||||
|
||||
```csharp
|
||||
services.AddSimApi(options =>
|
||||
{
|
||||
// 配置 Redis
|
||||
options.RedisConfiguration = "localhost:6379";
|
||||
|
||||
// 配置 API 文档
|
||||
options.EnableSimApiDoc = true;
|
||||
options.ConfigureSimApiDoc(docOptions =>
|
||||
{
|
||||
docOptions.ApiGroups = new[]
|
||||
{
|
||||
new SimApiDocGroupOption
|
||||
{
|
||||
Id = "admin",
|
||||
Name = "后台管理接口",
|
||||
Description = "本接口调用需要Scope:sac.api.admin"
|
||||
},
|
||||
new SimApiDocGroupOption
|
||||
{
|
||||
Id = "user-v1",
|
||||
Name = "用户中心接口",
|
||||
Description = "本接口调用需要Scope:sac.api.user"
|
||||
}
|
||||
};
|
||||
docOptions.ApiAuth = new SimApiAuthOption
|
||||
{
|
||||
Type = new[] { "ClientCredentials", "Implicit", "AuthorizationCode" },
|
||||
Scopes = new Dictionary<string, string>
|
||||
{
|
||||
{ "sac.api.user", "用户信息接口权限" },
|
||||
{ "sac.api.admin", "后台管理API" }
|
||||
},
|
||||
AuthorizationUrl = "/connect/authorize",
|
||||
TokenUrl = "/connect/token"
|
||||
};
|
||||
});
|
||||
|
||||
// 配置存储服务
|
||||
options.EnableSimApiStorage = true;
|
||||
options.SimApiStorageOptions = Configuration.GetSection("S3").Get<SimApiStorageOptions>();
|
||||
|
||||
// 配置任务调度
|
||||
options.EnableJob = true;
|
||||
options.ConfigureSimApiJob(jobOptions =>
|
||||
{
|
||||
jobOptions.DashboardUrl = "/jobs";
|
||||
jobOptions.DashboardAuthUser = "admin";
|
||||
jobOptions.DashboardAuthPass = "Admin@123!";
|
||||
});
|
||||
|
||||
// 配置事件和 RPC
|
||||
options.EnableSynapse = true;
|
||||
|
||||
// 其他配置
|
||||
options.EnableCors = true;
|
||||
options.EnableSimApiException = true;
|
||||
options.EnableSimApiResponseFilter = true;
|
||||
options.EnableVersionUrl = true;
|
||||
options.EnableLogger = true;
|
||||
});
|
||||
|
||||
// 使用 SimApi
|
||||
app.UseSimApi();
|
||||
```
|
||||
|
||||
### 6.2 控制器示例
|
||||
|
||||
```csharp
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SimApi.Controllers;
|
||||
using SimApi.Helpers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class UserController : BaseController
|
||||
{
|
||||
private readonly SimApiStorage _storage;
|
||||
|
||||
public UserController(SimApiStorage storage)
|
||||
{
|
||||
_storage = storage;
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public SimApiBaseResponse<User> GetUser(int id)
|
||||
{
|
||||
var user = GetUserFromDatabase(id);
|
||||
ErrorWhenNull(user, 404, "用户不存在");
|
||||
return new SimApiBaseResponse<User>(user);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[SimApiAuth] // 需要认证
|
||||
public SimApiBaseResponse<User> CreateUser(UserCreateDto dto)
|
||||
{
|
||||
ErrorWhen(string.IsNullOrEmpty(dto.Name), 400, "用户名不能为空");
|
||||
ErrorWhen(dto.Age < 18, 400, "年龄必须大于18岁");
|
||||
|
||||
var user = CreateUserInDatabase(dto);
|
||||
return new SimApiBaseResponse<User>(user);
|
||||
}
|
||||
|
||||
[HttpPost("upload-avatar")]
|
||||
[SimApiAuth]
|
||||
public async Task<SimApiBaseResponse<string>> UploadAvatar(IFormFile file)
|
||||
{
|
||||
using var stream = file.OpenReadStream();
|
||||
var path = $"/avatars/{LoginInfo.Id}/{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
|
||||
_storage.UploadFile(path, stream, file.ContentType);
|
||||
var url = _storage.GetUrl(path);
|
||||
return new SimApiBaseResponse<string>(url);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 6.3 任务调度示例
|
||||
|
||||
```csharp
|
||||
public class UserService
|
||||
{
|
||||
public void SendWelcomeEmail(string email)
|
||||
{
|
||||
// 发送欢迎邮件
|
||||
Console.WriteLine($"Sending welcome email to {email}");
|
||||
}
|
||||
|
||||
public void CleanupInactiveUsers()
|
||||
{
|
||||
// 清理不活跃用户
|
||||
Console.WriteLine("Cleaning up inactive users");
|
||||
}
|
||||
|
||||
public void GenerateMonthlyReport()
|
||||
{
|
||||
// 生成月度报告
|
||||
Console.WriteLine("Generating monthly report");
|
||||
}
|
||||
}
|
||||
|
||||
// 配置任务
|
||||
public void ConfigureJobs(IServiceProvider serviceProvider)
|
||||
{
|
||||
// 立即发送欢迎邮件
|
||||
BackgroundJob.Enqueue<UserService>(x => x.SendWelcomeEmail("user@example.com"));
|
||||
|
||||
// 每天凌晨清理不活跃用户
|
||||
RecurringJob.AddOrUpdate<UserService>("cleanup-inactive-users", x => x.CleanupInactiveUsers(), Cron.Daily);
|
||||
|
||||
// 每月1日生成月度报告
|
||||
RecurringJob.AddOrUpdate<UserService>("generate-monthly-report", x => x.GenerateMonthlyReport(), "0 0 1 * *");
|
||||
}
|
||||
```
|
||||
|
||||
## 7. 最佳实践
|
||||
|
||||
### 7.1 控制器设计
|
||||
|
||||
- 所有控制器应继承自 `SimApiBaseController` 或其派生类
|
||||
- 使用 `Error` 和 `ErrorWhen` 系列方法进行错误处理
|
||||
- 对需要认证的接口使用 `[SimApiAuth]` 属性
|
||||
- 合理使用 API 分组,便于文档管理
|
||||
|
||||
### 7.2 存储管理
|
||||
|
||||
- 为不同类型的文件使用不同的存储路径结构
|
||||
- 合理设置文件 URL 的过期时间
|
||||
- 对上传的文件进行验证和处理
|
||||
- 考虑使用 CDN 加速文件访问
|
||||
|
||||
### 7.3 任务调度
|
||||
|
||||
- 合理设置任务的队列和优先级
|
||||
- 对长时间运行的任务进行分解
|
||||
- 监控任务的执行状态和结果
|
||||
- 合理设置任务的重试策略
|
||||
|
||||
### 7.4 事件和 RPC
|
||||
|
||||
- 为事件和 RPC 方法使用清晰的命名规范
|
||||
- 合理设计事件和 RPC 的数据结构
|
||||
- 考虑事件处理的幂等性
|
||||
- 监控事件和 RPC 的执行情况
|
||||
|
||||
### 7.5 配置管理
|
||||
|
||||
- 使用配置文件或环境变量管理配置
|
||||
- 对敏感配置进行加密处理
|
||||
- 不同环境使用不同的配置
|
||||
- 定期审查和更新配置
|
||||
|
||||
### 7.6 性能优化
|
||||
|
||||
- 合理使用缓存减少数据库访问
|
||||
- 对高频访问的接口进行优化
|
||||
- 考虑使用异步方法提高并发性能
|
||||
- 监控系统性能并进行调优
|
||||
|
||||
## 8. 故障排查
|
||||
|
||||
### 8.1 常见问题
|
||||
|
||||
#### 认证失败
|
||||
- 检查 Token 是否正确
|
||||
- 检查 Redis 是否正常运行
|
||||
- 检查认证中间件是否正确配置
|
||||
|
||||
#### 存储服务错误
|
||||
- 检查 S3 服务是否正常运行
|
||||
- 检查存储配置是否正确
|
||||
- 检查网络连接是否正常
|
||||
|
||||
#### 任务调度错误
|
||||
- 检查 Hangfire 仪表盘是否可访问
|
||||
- 检查 Redis 是否正常运行
|
||||
- 检查任务代码是否有异常
|
||||
|
||||
#### API 文档生成错误
|
||||
- 检查 Swagger 配置是否正确
|
||||
- 检查控制器和方法的注释是否完整
|
||||
- 检查模型类是否有循环引用
|
||||
|
||||
### 8.2 日志和监控
|
||||
|
||||
- 启用 `EnableLogger` 配置查看详细日志
|
||||
- 使用应用性能监控工具监控系统状态
|
||||
- 定期检查系统日志和错误报告
|
||||
- 设置关键指标的告警机制
|
||||
|
||||
## 9. 版本管理
|
||||
|
||||
- 访问 `/versions` 查看应用版本和 SimApi 版本
|
||||
- 定期更新 SimApi 到最新版本
|
||||
- 注意版本升级时的兼容性问题
|
||||
- 遵循语义化版本规范管理应用版本
|
||||
|
||||
## 10. 总结
|
||||
|
||||
SimApi 是一个功能丰富的 .NET 基础辅助包,提供了一系列实用功能,帮助开发者快速构建和部署 API 服务。通过合理配置和使用 SimApi,可以显著提高开发效率,减少重复代码,提高系统的可维护性和可靠性。
|
||||
|
||||
本说明书提供了 SimApi 的详细使用方法和最佳实践,希望能帮助开发者更好地使用这个库。如果有任何问题或建议,欢迎反馈和贡献。
|
||||
@@ -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 可以是任意类型(兼容所有类型)
|
||||
|
||||
@@ -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 = "请求成功",
|
||||
|
||||
@@ -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 处理 |
|
||||
Reference in New Issue
Block a user