Compare commits

..
5 Commits
10 changed files with 252 additions and 84 deletions
+3
View File
@@ -434,3 +434,6 @@ MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder # Ionide (cross platform F# VS Code tools) working folder
.ionide/ .ionide/
# BitFun snapshot data - auto managed
.bitfun/
+1 -1
View File
@@ -51,7 +51,7 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class PageResponse<T> public class PageResponse<T>
{ {
public T? List { get; set; } public T[] List { get; set; } = [];
public int Page { get; set; } = 1; public int Page { get; set; } = 1;
public int Count { get; set; } = 20; public int Count { get; set; } = 20;
public int Total { get; set; } public int Total { get; set; }
+13
View File
@@ -56,6 +56,12 @@ public class SimApiOptions
/// </summary> /// </summary>
public bool EnableSimApiResponseFilter { get; set; } = true; public bool EnableSimApiResponseFilter { get; set; } = true;
/// <summary>
/// 启用请求日志中间件
/// default: false
/// </summary>
public bool EnableRequestLog { get; set; }
/// <summary> /// <summary>
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers /// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
/// default: true /// default: true
@@ -104,6 +110,8 @@ public class SimApiOptions
public SimApiRouteOptions SimApiRouteOptions { get; set; } = new(); public SimApiRouteOptions SimApiRouteOptions { get; set; } = new();
public SimApiRequestLogOptions SimApiRequestLogOptions { get; set; } = new();
public void ConfigureSimApiRoute(Action<SimApiRouteOptions>? options = null) public void ConfigureSimApiRoute(Action<SimApiRouteOptions>? options = null)
{ {
options?.Invoke(SimApiRouteOptions); options?.Invoke(SimApiRouteOptions);
@@ -143,4 +151,9 @@ public class SimApiOptions
{ {
options?.Invoke(SimApiAuthCenterOptions); options?.Invoke(SimApiAuthCenterOptions);
} }
public void ConfigureSimApiRequestLog(Action<SimApiRequestLogOptions>? options = null)
{
options?.Invoke(SimApiRequestLogOptions);
}
} }
+14
View File
@@ -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; }
}
+7 -6
View File
@@ -30,7 +30,7 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
/// <param name="queries"></param> /// <param name="queries"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <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; url = Server + url;
var queryUrl = SignFields.Aggregate(string.Empty, var queryUrl = SignFields.Aggregate(string.Empty,
@@ -60,14 +60,14 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
/// <param name="body"></param> /// <param name="body"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public T? AesQuery<T>(string url, object body) public T AesQuery<T>(string url, object body)
{ {
url = Server + url; url = Server + url;
if (!string.IsNullOrEmpty(AppIdName)) if (!string.IsNullOrEmpty(AppIdName))
{ {
url += $"?{AppIdName}={AppId}"; url += $"?{AppIdName}={AppId}";
} }
logger?.LogDebug($"[HTTPCLIENT请求][加密前BODY] {url}\n{SimApiUtil.Json(body)}\n");
var req = new SimApiOneFieldRequest<string> var req = new SimApiOneFieldRequest<string>
{ {
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey) Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
@@ -83,8 +83,9 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
/// <param name="queries"></param> /// <param name="queries"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <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> var req = new SimApiOneFieldRequest<string>
{ {
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey) Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
@@ -100,7 +101,7 @@ public class SimApiHttpClient(SimApiOptions? apiOptions = null, ILogger<SimApiHt
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
/// <exception cref="SimApiException"></exception> /// <exception cref="SimApiException"></exception>
private T? Query<T>(string url, object? req) private T Query<T>(string url, object? req)
{ {
var http = new HttpClient(); var http = new HttpClient();
logger?.LogDebug($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n"); 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; var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result;
SimApiError.ErrorWhenNull(res, 500, "请求发生错误"); SimApiError.ErrorWhenNull(res, 500, "请求发生错误");
SimApiError.ErrorWhen(res.Code != 200, res.Code, res.Message); SimApiError.ErrorWhen(res.Code != 200, res.Code, res.Message);
return res.Data; return res.Data!;
} }
} }
+105
View File
@@ -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();
}
}
+17 -17
View File
@@ -38,7 +38,7 @@ app.Run();
所有接口输出 JSON,HTTP 状态码始终 `200`,错误信息在 `code` 字段: 所有接口输出 JSON,HTTP 状态码始终 `200`,错误信息在 `code` 字段:
| code | 含义 | | code | 含义 |
|------|------| | ---- | ---------- |
| 200 | 成功 | | 200 | 成功 |
| 204 | 无数据 | | 204 | 无数据 |
| 400 | 参数错误 | | 400 | 参数错误 |
@@ -147,18 +147,18 @@ public class SimApiBaseController : Controller
### 自动路由 ### 自动路由
| 路由 | 方法 | 条件 | 说明 | | 路由 | 方法 | 条件 | 说明 |
|------|------|------|------| | ----------------------- | -------- | -------------------------------------------- | ------------------------ |
| `/versions` | GET/POST | `EnableVersionUrl`(默认) | 返回 SimApi/App 版本 | | `/versions` | GET/POST | `VersionRoute != null`(默认) | 返回 SimApi/App 版本 |
| `/user/info` | POST | `EnableSimApiAuth` | 需登录,返回 LoginInfo | | `/user/info` | POST | `EnableSimApiAuth` + `UserInfoRoute != null` | 需登录,返回 LoginInfo |
| `/logout` | POST | `EnableSimApiAuth` | 退出登录(可自定义路由) | | `/auth/logout` | POST | `EnableSimApiAuth` + `LogoutRoute != null` | 退出登录(可自定义路由) |
| `/swagger` | GET | `EnableSimApiDoc` | Swagger UI | | `/swagger` | GET | `EnableSimApiDoc` | Swagger UI |
| `/jobs` | GET | `EnableJob` + DashboardUrl | Hangfire 控制台 | | `/jobs` | GET | `EnableJob` + `DashboardUrl != null` | Hangfire 控制台 |
| `/exception/{code:int}` | GET | 始终 | 错误反馈页面 | | `/exception/{code:int}` | GET | 始终 | 错误反馈页面 |
### 返回值规范 ### 返回值规范
| 场景 | 返回类型 | | 场景 | 返回类型 |
|------|----------| | ---------- | ------------------------- |
| 写操作 | `void` | | 写操作 | `void` |
| 单条查询 | 直接 Entity | | 单条查询 | 直接 Entity |
| 列表查询 | `Entity[]` | | 列表查询 | `Entity[]` |
@@ -322,7 +322,8 @@ public class MySignProvider : SimApiSignProviderBase
```csharp ```csharp
[SynapseEvent("order/created")] // 指定 eventName [SynapseEvent("order/created")] // 指定 eventName
[SynapseEvent] // 不指定 = 方法名 [SynapseEvent] // 不指定 = 方法名
// 参数: 0个 / 1个(string eventName) / 2个(string eventName, T data) // 参数: 1个(string eventName) / 2个(string eventName, T data)
// 注意: 至少需要1个参数
``` ```
### [SynapseRpc] — MQTT RPC 方法 ### [SynapseRpc] — MQTT RPC 方法
@@ -359,7 +360,7 @@ options.ConfigureSimApiDoc(doc =>
### 自动过滤器 ### 自动过滤器
| 过滤器 | 效果 | | 过滤器 | 效果 |
|--------|------| | --------------------------------- | ------------------------------------ |
| `SimApiResponseOperationFilter` | 返回值包装为 `SimApiBaseResponse<T>` | | `SimApiResponseOperationFilter` | 返回值包装为 `SimApiBaseResponse<T>` |
| `SimApiAuthOperationFilter` | 鉴权接口 + Token Header | | `SimApiAuthOperationFilter` | 鉴权接口 + Token Header |
| `SimApiSignOperationFilter` | 签名接口注入签名参数 | | `SimApiSignOperationFilter` | 签名接口注入签名参数 |
@@ -439,9 +440,9 @@ virtual string[] SignFields { get; init; } = [];
### 调用方法 ### 调用方法
```csharp ```csharp
T? SignQuery<T>(string url, object? body = null, 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 AesQuery<T>(string url, object body);
T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null); T AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null);
``` ```
--- ---
@@ -499,7 +500,7 @@ options.ConfigureSimApiSynapse(s =>
### Topic 规则 ### Topic 规则
| 用途 | Topic 格式 | | 用途 | Topic 格式 |
|------|-----------| | -------- | ------------------------------------------------------ |
| 事件发布 | `{SysName}/event/{AppName}/{eventName}` | | 事件发布 | `{SysName}/event/{AppName}/{eventName}` |
| 事件订阅 | `{SysName}/event/{eventName}` (或 `$queue/` 前缀) | | 事件订阅 | `{SysName}/event/{eventName}` (或 `$queue/` 前缀) |
| RPC 请求 | `{SysName}/{targetApp}/rpc/server/{method}` | | RPC 请求 | `{SysName}/{targetApp}/rpc/server/{method}` |
@@ -589,7 +590,7 @@ void UpdateTime();
## 15. DTO 规范 ## 15. DTO 规范
| 类型 | 命名 | 示例 | | 类型 | 命名 | 示例 |
|------|------|------| | ---- | ----------------- | ----------------- |
| 请求 | `[动作]Request` | `UserEditRequest` | | 请求 | `[动作]Request` | `UserEditRequest` |
| 响应 | `[动作]Response` | `TokenResponse` | | 响应 | `[动作]Response` | `TokenResponse` |
| 载体 | `[含义]Data/Item` | `GenerateData` | | 载体 | `[含义]Data/Item` | `GenerateData` |
@@ -628,7 +629,6 @@ builder.Services.AddSimApi(options =>
options.EnableSimApiResponseFilter = true; // 响应统一封装 options.EnableSimApiResponseFilter = true; // 响应统一封装
options.EnableForwardHeaders = true; // 反向代理 Header options.EnableForwardHeaders = true; // 反向代理 Header
options.EnableLowerUrl = true; // URL 小写 options.EnableLowerUrl = true; // URL 小写
options.EnableVersionUrl = true; // /versions 接口
// 子模块配置 // 子模块配置
options.ConfigureSimApiDoc(doc => { ... }); options.ConfigureSimApiDoc(doc => { ... });
@@ -647,7 +647,7 @@ builder.Services.AddSimApi(options =>
## 17. GOTCHAS — 常见错误 ## 17. GOTCHAS — 常见错误
| ❌ 错误 | ✅ 正确 | | ❌ 错误 | ✅ 正确 |
|---------|---------| | ------------------------------------------------------ | ------------------------------------------- |
| 存储路径 `avatars/file.jpg`(无前导 `/`) | 必须以 **`/`** 开头 | | 存储路径 `avatars/file.jpg`(无前导 `/`) | 必须以 **`/`** 开头 |
| `s.Endpoint = "http://x:9000/"` | **不能以 `/` 结尾** | | `s.Endpoint = "http://x:9000/"` | **不能以 `/` 结尾** |
| `synapse.PublishEvent(...)` | 方法名是 **`synapse.Event(...)`** | | `synapse.PublishEvent(...)` | 方法名是 **`synapse.Event(...)`** |
@@ -662,7 +662,7 @@ builder.Services.AddSimApi(options =>
## 18. 禁止事项 ## 18. 禁止事项
| ❌ 禁止 | ✅ 正确 | | ❌ 禁止 | ✅ 正确 |
|---------|------------------------------------------------------| | --------------------------------------- | ----------------------------------------------------- |
| HTTP 4xx/5xx 表达业务错误 | HTTP 200 + JSON `code` | | HTTP 4xx/5xx 表达业务错误 | HTTP 200 + JSON `code` |
| `throw new Exception(msg)` | `ErrorWhen``throw new SimApiException(code, msg)` | | `throw new Exception(msg)` | `ErrorWhen``throw new SimApiException(code, msg)` |
| 鉴权 Attribute 只放方法 | 可以放 Controller **类**上 | | 鉴权 Attribute 只放方法 | 可以放 Controller **类**上 |
+5 -5
View File
@@ -12,13 +12,13 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <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.Console" Version="1.4.3"/>
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0"/> <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="Minio" Version="7.0.0" />
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/> <PackageReference Include="MQTTnet" Version="5.1.0.1559" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.0" /> <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" /> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.2.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+8
View File
@@ -209,6 +209,7 @@ public static class SimApiExtensions
x.OperationFilter<SimApiSignOperationFilter>(); x.OperationFilter<SimApiSignOperationFilter>();
x.OperationFilter<AesBodyOperationFilter>(); x.OperationFilter<AesBodyOperationFilter>();
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>(); x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
x.SchemaFilter<DictionarySchemaFilter>();
x.DocumentFilter<RemoveEmptyTagsFilter>(); x.DocumentFilter<RemoveEmptyTagsFilter>();
if (simApiOptions.EnableSimApiAuth) if (simApiOptions.EnableSimApiAuth)
{ {
@@ -339,6 +340,7 @@ public static class SimApiExtensions
} }
} }
builder.AddSingleton(simApiOptions.SimApiRequestLogOptions);
builder.AddSingleton(simApiOptions); builder.AddSingleton(simApiOptions);
return builder; return builder;
} }
@@ -497,6 +499,12 @@ public static class SimApiExtensions
}); });
} }
if (options.EnableRequestLog)
{
logger.LogInformation("开始配置SimApiRequestLog...");
builder.UseMiddleware<SimApiRequestLogMiddleware>();
}
if (options.EnableSimApiException) if (options.EnableSimApiException)
{ {
logger.LogInformation("开始配置SimApiException..."); logger.LogInformation("开始配置SimApiException...");
+24
View File
@@ -0,0 +1,24 @@
using System.Collections.Generic;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace SimApi.SwaggerFilters;
public class DictionarySchemaFilter : ISchemaFilter
{
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
{
if (!context.Type.IsGenericType || context.Type.GetGenericTypeDefinition() != typeof(Dictionary<,>))
return;
if (schema is not OpenApiSchema concrete) return;
var valueType = context.Type.GetGenericArguments()[1];
concrete.Type = JsonSchemaType.Object;
concrete.AdditionalPropertiesAllowed = true;
concrete.AdditionalProperties = context.SchemaGenerator.GenerateSchema(valueType, context.SchemaRepository);
concrete.Properties?.Clear();
concrete.Example = null;
concrete.Examples?.Clear();
}
}