Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c5081d442 | ||
|
|
2ed4605a2c | ||
|
|
ceeea2c451 | ||
|
|
464878edce |
@@ -434,3 +434,6 @@ MigrationBackup/
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
|
||||
# BitFun snapshot data - auto managed
|
||||
.bitfun/
|
||||
|
||||
@@ -51,7 +51,7 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class PageResponse<T>
|
||||
{
|
||||
public T? List { get; set; }
|
||||
public T[] List { get; set; } = [];
|
||||
public int Page { get; set; } = 1;
|
||||
public int Count { get; set; } = 20;
|
||||
public int Total { get; set; }
|
||||
|
||||
@@ -56,6 +56,12 @@ public class SimApiOptions
|
||||
/// </summary>
|
||||
public bool EnableSimApiResponseFilter { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 启用请求日志中间件
|
||||
/// default: false
|
||||
/// </summary>
|
||||
public bool EnableRequestLog { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
||||
/// default: true
|
||||
@@ -104,6 +110,8 @@ public class SimApiOptions
|
||||
|
||||
public SimApiRouteOptions SimApiRouteOptions { get; set; } = new();
|
||||
|
||||
public SimApiRequestLogOptions SimApiRequestLogOptions { get; set; } = new();
|
||||
|
||||
public void ConfigureSimApiRoute(Action<SimApiRouteOptions>? options = null)
|
||||
{
|
||||
options?.Invoke(SimApiRouteOptions);
|
||||
@@ -143,4 +151,9 @@ public class SimApiOptions
|
||||
{
|
||||
options?.Invoke(SimApiAuthCenterOptions);
|
||||
}
|
||||
|
||||
public void ConfigureSimApiRequestLog(Action<SimApiRequestLogOptions>? options = null)
|
||||
{
|
||||
options?.Invoke(SimApiRequestLogOptions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace SimApi.Configurations;
|
||||
|
||||
public class SimApiRequestLogOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否打印完整的请求Header
|
||||
/// </summary>
|
||||
public bool ShowFullHeader { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否打印完整的响应体
|
||||
/// </summary>
|
||||
public bool ShowFullResponse { get; set; }
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
|
||||
/// <param name="queries"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
|
||||
public T SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
|
||||
{
|
||||
url = Server + url;
|
||||
var queryUrl = SignFields.Aggregate(string.Empty,
|
||||
@@ -60,14 +60,14 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
|
||||
/// <param name="body"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public T? AesQuery<T>(string url, object body)
|
||||
public T AesQuery<T>(string url, object body)
|
||||
{
|
||||
url = Server + url;
|
||||
if (!string.IsNullOrEmpty(AppIdName))
|
||||
{
|
||||
url += $"?{AppIdName}={AppId}";
|
||||
}
|
||||
|
||||
logger?.LogDebug($"[HTTPCLIENT请求][加密前BODY] {url}\n{SimApiUtil.Json(body)}\n");
|
||||
var req = new SimApiOneFieldRequest<string>
|
||||
{
|
||||
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
|
||||
@@ -83,8 +83,9 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
|
||||
/// <param name="queries"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
||||
public T AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
||||
{
|
||||
logger?.LogDebug($"[HTTPCLIENT请求][加密前BODY] {url}\n{SimApiUtil.Json(body)}\n");
|
||||
var req = new SimApiOneFieldRequest<string>
|
||||
{
|
||||
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
|
||||
@@ -100,7 +101,7 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="SimApiException"></exception>
|
||||
private T? Query<T>(string url, object? req)
|
||||
private T Query<T>(string url, object? req)
|
||||
{
|
||||
var http = new HttpClient();
|
||||
logger?.LogDebug($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
|
||||
@@ -110,6 +111,6 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
|
||||
var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result;
|
||||
SimApiError.ErrorWhenNull(res, 500, "请求发生错误");
|
||||
SimApiError.ErrorWhen(res.Code != 200, res.Code, res.Message);
|
||||
return res.Data;
|
||||
return res.Data!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SimApi.Configurations;
|
||||
|
||||
namespace SimApi.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// 请求日志中间件
|
||||
/// </summary>
|
||||
public class SimApiRequestLogMiddleware(
|
||||
RequestDelegate next,
|
||||
ILogger<SimApiRequestLogMiddleware> log,
|
||||
SimApiRequestLogOptions options)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var fullUrl =
|
||||
$"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
|
||||
|
||||
var logMessage = new StringBuilder();
|
||||
logMessage.AppendLine($"[{context.Request.Method}] {fullUrl}");
|
||||
|
||||
if (options.ShowFullHeader)
|
||||
{
|
||||
logMessage.AppendLine("*( RequestHeaders [Full] ) =>");
|
||||
var headersDict = new Dictionary<string, string>();
|
||||
foreach (var header in context.Request.Headers)
|
||||
{
|
||||
headersDict[header.Key] = header.Value.ToString();
|
||||
}
|
||||
|
||||
logMessage.AppendLine(JsonSerializer.Serialize(headersDict));
|
||||
}
|
||||
else
|
||||
{
|
||||
logMessage.AppendLine("*( RequestHeaders ) =>");
|
||||
var token = context.Request.Headers["Token"].FirstOrDefault() ?? "";
|
||||
var queryId = context.Request.Headers["Query-Id"].FirstOrDefault() ?? "";
|
||||
logMessage.AppendLine($"Token: {token} QueryId: {queryId}");
|
||||
}
|
||||
|
||||
context.Request.EnableBuffering();
|
||||
var requestBodyText = await new StreamReader(context.Request.Body).ReadToEndAsync();
|
||||
context.Request.Body.Seek(0, SeekOrigin.Begin);
|
||||
logMessage.AppendLine("*( RequestBody ) =>");
|
||||
logMessage.AppendLine(requestBodyText);
|
||||
|
||||
var originalBodyStream = context.Response.Body;
|
||||
using var responseBody = new MemoryStream();
|
||||
context.Response.Body = responseBody;
|
||||
|
||||
ExceptionDispatchInfo? edi = null;
|
||||
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
edi = ExceptionDispatchInfo.Capture(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
sw.Stop();
|
||||
|
||||
responseBody.Seek(0, SeekOrigin.Begin);
|
||||
var responseText = await new StreamReader(responseBody).ReadToEndAsync();
|
||||
|
||||
logMessage.AppendLine($"*( Response [{context.Response.StatusCode}] ) =>");
|
||||
if (options.ShowFullResponse)
|
||||
{
|
||||
logMessage.Append(responseText);
|
||||
}
|
||||
else
|
||||
{
|
||||
var truncated = responseText.Length > 200 ? responseText[..200] : responseText;
|
||||
logMessage.Append(truncated);
|
||||
}
|
||||
|
||||
if (edi != null)
|
||||
{
|
||||
logMessage.Append(Environment.NewLine);
|
||||
logMessage.Append($"Exception: {edi.SourceException}");
|
||||
}
|
||||
|
||||
responseBody.Seek(0, SeekOrigin.Begin);
|
||||
await responseBody.CopyToAsync(originalBodyStream);
|
||||
context.Response.Body = originalBodyStream;
|
||||
|
||||
log.LogInformation(logMessage.ToString());
|
||||
}
|
||||
|
||||
edi?.Throw();
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ app.Run();
|
||||
所有接口输出 JSON,HTTP 状态码始终 `200`,错误信息在 `code` 字段:
|
||||
|
||||
| code | 含义 |
|
||||
|------|------|
|
||||
| ---- | ---------- |
|
||||
| 200 | 成功 |
|
||||
| 204 | 无数据 |
|
||||
| 400 | 参数错误 |
|
||||
@@ -147,18 +147,18 @@ public class SimApiBaseController : Controller
|
||||
### 自动路由
|
||||
|
||||
| 路由 | 方法 | 条件 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `/versions` | GET/POST | `EnableVersionUrl`(默认) | 返回 SimApi/App 版本 |
|
||||
| `/user/info` | POST | `EnableSimApiAuth` | 需登录,返回 LoginInfo |
|
||||
| `/logout` | POST | `EnableSimApiAuth` | 退出登录(可自定义路由) |
|
||||
| ----------------------- | -------- | -------------------------------------------- | ------------------------ |
|
||||
| `/versions` | GET/POST | `VersionRoute != null`(默认) | 返回 SimApi/App 版本 |
|
||||
| `/user/info` | POST | `EnableSimApiAuth` + `UserInfoRoute != null` | 需登录,返回 LoginInfo |
|
||||
| `/auth/logout` | POST | `EnableSimApiAuth` + `LogoutRoute != null` | 退出登录(可自定义路由) |
|
||||
| `/swagger` | GET | `EnableSimApiDoc` | Swagger UI |
|
||||
| `/jobs` | GET | `EnableJob` + DashboardUrl | Hangfire 控制台 |
|
||||
| `/jobs` | GET | `EnableJob` + `DashboardUrl != null` | Hangfire 控制台 |
|
||||
| `/exception/{code:int}` | GET | 始终 | 错误反馈页面 |
|
||||
|
||||
### 返回值规范
|
||||
|
||||
| 场景 | 返回类型 |
|
||||
|------|----------|
|
||||
| ---------- | ------------------------- |
|
||||
| 写操作 | `void` |
|
||||
| 单条查询 | 直接 Entity |
|
||||
| 列表查询 | `Entity[]` |
|
||||
@@ -322,7 +322,8 @@ public class MySignProvider : SimApiSignProviderBase
|
||||
```csharp
|
||||
[SynapseEvent("order/created")] // 指定 eventName
|
||||
[SynapseEvent] // 不指定 = 方法名
|
||||
// 参数: 0个 / 1个(string eventName) / 2个(string eventName, T data)
|
||||
// 参数: 1个(string eventName) / 2个(string eventName, T data)
|
||||
// 注意: 至少需要1个参数
|
||||
```
|
||||
|
||||
### [SynapseRpc] — MQTT RPC 方法
|
||||
@@ -359,7 +360,7 @@ options.ConfigureSimApiDoc(doc =>
|
||||
### 自动过滤器
|
||||
|
||||
| 过滤器 | 效果 |
|
||||
|--------|------|
|
||||
| --------------------------------- | ------------------------------------ |
|
||||
| `SimApiResponseOperationFilter` | 返回值包装为 `SimApiBaseResponse<T>` |
|
||||
| `SimApiAuthOperationFilter` | 鉴权接口 + Token Header |
|
||||
| `SimApiSignOperationFilter` | 签名接口注入签名参数 |
|
||||
@@ -439,9 +440,9 @@ virtual string[] SignFields { get; init; } = [];
|
||||
### 调用方法
|
||||
|
||||
```csharp
|
||||
T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null);
|
||||
T? AesQuery<T>(string url, object body);
|
||||
T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null);
|
||||
T SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null);
|
||||
T AesQuery<T>(string url, object body);
|
||||
T AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null);
|
||||
```
|
||||
|
||||
---
|
||||
@@ -499,7 +500,7 @@ options.ConfigureSimApiSynapse(s =>
|
||||
### Topic 规则
|
||||
|
||||
| 用途 | Topic 格式 |
|
||||
|------|-----------|
|
||||
| -------- | ------------------------------------------------------ |
|
||||
| 事件发布 | `{SysName}/event/{AppName}/{eventName}` |
|
||||
| 事件订阅 | `{SysName}/event/{eventName}` (或 `$queue/` 前缀) |
|
||||
| RPC 请求 | `{SysName}/{targetApp}/rpc/server/{method}` |
|
||||
@@ -589,7 +590,7 @@ void UpdateTime();
|
||||
## 15. DTO 规范
|
||||
|
||||
| 类型 | 命名 | 示例 |
|
||||
|------|------|------|
|
||||
| ---- | ----------------- | ----------------- |
|
||||
| 请求 | `[动作]Request` | `UserEditRequest` |
|
||||
| 响应 | `[动作]Response` | `TokenResponse` |
|
||||
| 载体 | `[含义]Data/Item` | `GenerateData` |
|
||||
@@ -628,7 +629,6 @@ builder.Services.AddSimApi(options =>
|
||||
options.EnableSimApiResponseFilter = true; // 响应统一封装
|
||||
options.EnableForwardHeaders = true; // 反向代理 Header
|
||||
options.EnableLowerUrl = true; // URL 小写
|
||||
options.EnableVersionUrl = true; // /versions 接口
|
||||
|
||||
// 子模块配置
|
||||
options.ConfigureSimApiDoc(doc => { ... });
|
||||
@@ -647,7 +647,7 @@ builder.Services.AddSimApi(options =>
|
||||
## 17. GOTCHAS — 常见错误
|
||||
|
||||
| ❌ 错误 | ✅ 正确 |
|
||||
|---------|---------|
|
||||
| ------------------------------------------------------ | ------------------------------------------- |
|
||||
| 存储路径 `avatars/file.jpg`(无前导 `/`) | 必须以 **`/`** 开头 |
|
||||
| `s.Endpoint = "http://x:9000/"` | **不能以 `/` 结尾** |
|
||||
| `synapse.PublishEvent(...)` | 方法名是 **`synapse.Event(...)`** |
|
||||
@@ -662,7 +662,7 @@ builder.Services.AddSimApi(options =>
|
||||
## 18. 禁止事项
|
||||
|
||||
| ❌ 禁止 | ✅ 正确 |
|
||||
|---------|------------------------------------------------------|
|
||||
| --------------------------------------- | ----------------------------------------------------- |
|
||||
| HTTP 4xx/5xx 表达业务错误 | HTTP 200 + JSON `code` |
|
||||
| `throw new Exception(msg)` | `ErrorWhen` 或 `throw new SimApiException(code, msg)` |
|
||||
| 鉴权 Attribute 只放方法 | 可以放 Controller **类**上 |
|
||||
|
||||
+5
-5
@@ -12,13 +12,13 @@
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
|
||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.23" />
|
||||
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
|
||||
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.9" />
|
||||
<PackageReference Include="Minio" Version="7.0.0" />
|
||||
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
|
||||
<PackageReference Include="MQTTnet" Version="5.1.0.1559" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.2.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.2.3" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -339,6 +339,7 @@ public static class SimApiExtensions
|
||||
}
|
||||
}
|
||||
|
||||
builder.AddSingleton(simApiOptions.SimApiRequestLogOptions);
|
||||
builder.AddSingleton(simApiOptions);
|
||||
return builder;
|
||||
}
|
||||
@@ -497,6 +498,12 @@ public static class SimApiExtensions
|
||||
});
|
||||
}
|
||||
|
||||
if (options.EnableRequestLog)
|
||||
{
|
||||
logger.LogInformation("开始配置SimApiRequestLog...");
|
||||
builder.UseMiddleware<SimApiRequestLogMiddleware>();
|
||||
}
|
||||
|
||||
if (options.EnableSimApiException)
|
||||
{
|
||||
logger.LogInformation("开始配置SimApiException...");
|
||||
|
||||
Reference in New Issue
Block a user