Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
140e039d27 | ||
|
|
3b263b4563 | ||
|
|
fc7b38ac4e | ||
|
|
e3fc7db01c | ||
|
|
894d6930f7 | ||
|
|
106d3eec19 | ||
|
|
a8c7a20a64 | ||
|
|
b6dbcd6cee | ||
|
|
b7775cbe6c | ||
|
|
28c6d53f38 | ||
|
|
ebceb0a260 | ||
|
|
162b92a415 | ||
|
|
a859986a93 | ||
|
|
e1c6694e18 | ||
|
|
566b1d190b | ||
|
|
eb8c9732bd |
@@ -1,9 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.AspNetCore.Mvc.Filters;
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
|
using SimApi.Interfaces;
|
||||||
|
using static SimApi.Helpers.SimApiError;
|
||||||
|
|
||||||
namespace SimApi.Attributes;
|
namespace SimApi.Attributes;
|
||||||
|
|
||||||
@@ -37,17 +39,16 @@ public class SimApiAuthAttribute : ActionFilterAttribute
|
|||||||
public override void OnActionExecuting(ActionExecutingContext context)
|
public override void OnActionExecuting(ActionExecutingContext context)
|
||||||
{
|
{
|
||||||
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
|
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
|
||||||
//检测是否登录
|
var token = (string)context.HttpContext.Items["LoginToken"]!;
|
||||||
if (loginInfo == null)
|
ErrorWhenNull(loginInfo, 401);
|
||||||
|
var checkers = context.HttpContext.RequestServices.GetServices<ISimApiAuthChecker>();
|
||||||
|
foreach (var checker in checkers)
|
||||||
{
|
{
|
||||||
throw new SimApiException(401);
|
checker.Run(loginInfo, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Types == null) return;
|
if (Types == null) return;
|
||||||
//检测用户类型
|
//检测用户类型
|
||||||
if (!Types.Intersect(loginInfo.Type).Any())
|
ErrorWhenFalse(Types.Intersect(loginInfo.Type).Any(), 403);
|
||||||
{
|
|
||||||
throw new SimApiException(403);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+4
-5
@@ -14,7 +14,6 @@ namespace SimApi.CoceSdk;
|
|||||||
|
|
||||||
public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache)
|
public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache)
|
||||||
{
|
{
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取Level Token
|
/// 获取Level Token
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -164,7 +163,7 @@ public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDist
|
|||||||
var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey);
|
var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey);
|
||||||
logger.LogDebug("签名: {Sign}", sign);
|
logger.LogDebug("签名: {Sign}", sign);
|
||||||
request.Add("sign", sign);
|
request.Add("sign", sign);
|
||||||
logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, JsonSerializer.Serialize(request));
|
logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, SimApiUtil.Json(request));
|
||||||
var http = new HttpClient();
|
var http = new HttpClient();
|
||||||
return http.PostAsJsonAsync(platUrl, request).Result;
|
return http.PostAsJsonAsync(platUrl, request).Result;
|
||||||
}
|
}
|
||||||
@@ -178,7 +177,7 @@ public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDist
|
|||||||
public IEnumerable<GroupInfo>? GetUserGroups(string token)
|
public IEnumerable<GroupInfo>? GetUserGroups(string token)
|
||||||
{
|
{
|
||||||
const string uri = "/api/lv2/user/groups";
|
const string uri = "/api/lv2/user/groups";
|
||||||
var resp = ProxyQuery<GroupInfo[]>(uri, token,"{}");
|
var resp = ProxyQuery<GroupInfo[]>(uri, token, "{}");
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,10 +206,10 @@ public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDist
|
|||||||
public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json);
|
public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json);
|
||||||
|
|
||||||
public dynamic? ProxyQueue(string uri, string token, object data) =>
|
public dynamic? ProxyQueue(string uri, string token, object data) =>
|
||||||
ProxyQuery<dynamic>(uri, token, JsonSerializer.Serialize(data));
|
ProxyQuery<dynamic>(uri, token, SimApiUtil.Json(data));
|
||||||
|
|
||||||
public T? ProxyQueue<T>(string uri, string token, object data) =>
|
public T? ProxyQueue<T>(string uri, string token, object data) =>
|
||||||
ProxyQuery<T>(uri, token, JsonSerializer.Serialize(data));
|
ProxyQuery<T>(uri, token, SimApiUtil.Json(data));
|
||||||
|
|
||||||
public T? ProxyQuery<T>(string uri, string token, string json = "{}")
|
public T? ProxyQuery<T>(string uri, string token, string json = "{}")
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ using SimApi.Attributes;
|
|||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Controllers;
|
using SimApi.Controllers;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
using static SimApi.Helpers.SimApiError;
|
||||||
|
|
||||||
namespace SimApi.CoceSdk;
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
@@ -19,7 +20,7 @@ public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public SimApiBaseResponse<string> Login([FromBody] SimApiOneFieldRequest<string> request)
|
public string Login([FromBody] SimApiOneFieldRequest<string> request)
|
||||||
{
|
{
|
||||||
var data = coce.GetLevelToken(request.Data!);
|
var data = coce.GetLevelToken(request.Data!);
|
||||||
ErrorWhenNull(data, 400);
|
ErrorWhenNull(data, 400);
|
||||||
@@ -38,14 +39,14 @@ public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp)
|
|||||||
};
|
};
|
||||||
var processor = sp.GetService<ICoceLoginProcessor>();
|
var processor = sp.GetService<ICoceLoginProcessor>();
|
||||||
processor?.Process(loginItem, groups.ToArray());
|
processor?.Process(loginItem, groups.ToArray());
|
||||||
return new SimApiBaseResponse<string>(auth.Login(loginItem));
|
return auth.Login(loginItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost, SimApiAuth]
|
[HttpPost, SimApiAuth]
|
||||||
public SimApiBaseResponse<GroupInfo[]> ListGroups()
|
public GroupInfo[] ListGroups()
|
||||||
{
|
{
|
||||||
var levelToken = coce.GetToken(LoginInfo.Id!);
|
var levelToken = coce.GetToken(LoginInfo.Id!);
|
||||||
var groups = coce.GetUserGroups(levelToken!)!;
|
var groups = coce.GetUserGroups(levelToken!)!;
|
||||||
return new SimApiBaseResponse<GroupInfo[]>(groups.ToArray());
|
return groups.ToArray();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -27,11 +27,11 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
|||||||
{ 400, "参数错误" },
|
{ 400, "参数错误" },
|
||||||
{ 401, "需要登录" },
|
{ 401, "需要登录" },
|
||||||
{ 403, "无权访问" },
|
{ 403, "无权访问" },
|
||||||
{ 404, "接口不存在" },
|
{ 404, "请求资源不存在" },
|
||||||
{ 500, "服务器错误" }
|
{ 500, "服务器错误" }
|
||||||
};
|
};
|
||||||
|
|
||||||
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误"))
|
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误代码"))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,5 +10,5 @@ public class SimApiLoginItem
|
|||||||
public required string Id { get; set; }
|
public required string Id { get; set; }
|
||||||
public string[] Type { get; set; } = ["user"];
|
public string[] Type { get; set; } = ["user"];
|
||||||
public Dictionary<string, string> Meta { get; set; } = [];
|
public Dictionary<string, string> Meta { get; set; } = [];
|
||||||
public object? Extra { get; set; }
|
public Dictionary<string, object?> Extra { get; set; } = [];
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
public class SimApiGateAuthOptions
|
||||||
|
{
|
||||||
|
public string? AppId { get; set; }
|
||||||
|
|
||||||
|
public string? AppKey { get; set; }
|
||||||
|
}
|
||||||
@@ -29,11 +29,12 @@ public class SimApiJobOptions
|
|||||||
/// 设置为null 使用默认redis配置
|
/// 设置为null 使用默认redis配置
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int? Database { get; set; } = null;
|
public int? Database { get; set; } = null;
|
||||||
|
|
||||||
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
||||||
}
|
}
|
||||||
|
|
||||||
public class SimApiJobServerConfig()
|
public class SimApiJobServerConfig()
|
||||||
{
|
{
|
||||||
public string[] Queues { get; set; } = ["default"];
|
public string[] Queues { get; set; } = ["default"];
|
||||||
public int WorkerNum { get; set; } = 50;
|
public int WorkerNum { get; set; } = 5;
|
||||||
}
|
}
|
||||||
@@ -18,6 +18,11 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiAuth { get; set; }
|
public bool EnableSimApiAuth { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启用SimApi网关授权, 基于上层网关透传的身份令牌验证
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSimApiGateAuth { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否使用CoceSdk
|
/// 是否使用CoceSdk
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -81,7 +86,6 @@ public class SimApiOptions
|
|||||||
public bool EnableVersionUrl { get; set; } = true;
|
public bool EnableVersionUrl { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用格式化的 Console Logger
|
/// 启用格式化的 Console Logger
|
||||||
/// default: false
|
/// default: false
|
||||||
@@ -106,6 +110,8 @@ public class SimApiOptions
|
|||||||
|
|
||||||
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
|
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
|
||||||
|
|
||||||
|
public SimApiGateAuthOptions SimApiGateAuthOptions { get; set; } = new();
|
||||||
|
|
||||||
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
|
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiSynapseOptions);
|
options?.Invoke(SimApiSynapseOptions);
|
||||||
@@ -130,4 +136,9 @@ public class SimApiOptions
|
|||||||
{
|
{
|
||||||
options?.Invoke(SimApiJobOptions);
|
options?.Invoke(SimApiJobOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ConfigureSimApiGateAuth(Action<SimApiGateAuthOptions>? options = null)
|
||||||
|
{
|
||||||
|
options?.Invoke(SimApiGateAuthOptions);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,49 +1,24 @@
|
|||||||
using System.Collections.Generic;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Controllers;
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
|
using static SimApiError;
|
||||||
|
|
||||||
public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
|
public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 检测用户登陆的控制器
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost, SimApiDoc("认证", "检测登陆")]
|
|
||||||
public SimApiBaseResponse<string> CheckLogin()
|
|
||||||
{
|
|
||||||
ErrorWhenNull(LoginInfo, 401, "未登录");
|
|
||||||
return new SimApiBaseResponse<string>
|
|
||||||
{
|
|
||||||
Data = LoginInfo.Id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 退出登陆
|
/// 退出登陆
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost, SimApiDoc("认证", "退出登陆")]
|
[HttpPost, SimApiDoc("认证", "退出登陆")]
|
||||||
public SimApiBaseResponse Logout()
|
public void Logout()
|
||||||
{
|
{
|
||||||
string? token = null;
|
|
||||||
|
|
||||||
if (Request.Headers.TryGetValue("Token", out var value))
|
if (Request.Headers.TryGetValue("Token", out var value))
|
||||||
{
|
{
|
||||||
token = value;
|
auth.Logout(value!);
|
||||||
}
|
}
|
||||||
|
|
||||||
auth.Logout(token!);
|
|
||||||
return new SimApiBaseResponse();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
[HttpPost, SimApiAuth]
|
|
||||||
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
|
||||||
{
|
|
||||||
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
using System.Diagnostics.CodeAnalysis;
|
using SimApi.Communications;
|
||||||
using SimApi.Communications;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Mvc.Filters;
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using SimApi.Exceptions;
|
using static SimApi.Helpers.SimApiError;
|
||||||
|
|
||||||
namespace SimApi.Controllers;
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
@@ -24,6 +23,8 @@ public class SimApiBaseController : Controller
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
|
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
|
||||||
|
|
||||||
|
protected string LoginToken => (string)HttpContext.Items["LoginToken"]!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 验证请求参数
|
/// 验证请求参数
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -38,74 +39,4 @@ public class SimApiBaseController : Controller
|
|||||||
break;
|
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>();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
using static SimApi.Helpers.SimApiError;
|
||||||
|
|
||||||
namespace SimApi.Controllers;
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
@@ -14,22 +16,26 @@ public class SimApiCommonController : SimApiBaseController
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("exception/{code:int}")]
|
[HttpGet("exception/{code:int}")]
|
||||||
[ApiExplorerSettings(IgnoreApi = true)]
|
[ApiExplorerSettings(IgnoreApi = true)]
|
||||||
public SimApiBaseResponse ExceptionHandler(int code)
|
public void ExceptionHandler(int code)
|
||||||
{
|
{
|
||||||
return new SimApiBaseResponse(code);
|
Error(code);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[HttpPost, HttpGet]
|
[HttpPost, HttpGet]
|
||||||
public SimApiBaseResponse<Dictionary<string, string>> Versions()
|
public Dictionary<string, string> Versions()
|
||||||
{
|
{
|
||||||
return new SimApiBaseResponse<Dictionary<string, string>>()
|
return new Dictionary<string, string>
|
||||||
{
|
{
|
||||||
Data = new Dictionary<string, string>
|
{ "SimApi", SimApiUtil.SimApiVersion },
|
||||||
{
|
{ "App", SimApiUtil.AppVersion }
|
||||||
{ "SimApi", SimApiUtil.SimApiVersion },
|
|
||||||
{ "App", SimApiUtil.AppVersion }
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取已登录用户信息
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("/user/info"), SimApiAuth, SimApiDoc("认证", "获取已登录用户信息")]
|
||||||
|
public SimApiLoginItem UserInfo() => LoginInfo;
|
||||||
}
|
}
|
||||||
+95
-11
@@ -1,25 +1,41 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Text.Json;
|
using System.Collections.Generic;
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
using StackExchange.Redis;
|
||||||
|
|
||||||
namespace SimApi.Helpers;
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 认证助手
|
/// 认证助手
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiAuth(IDistributedCache cache)
|
public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
|
||||||
{
|
{
|
||||||
|
private const string TokenCacheKey = "SimApi:Auth:Token:{token}";
|
||||||
|
private const string TokenSetCacheKey = "SimApi:Auth:User:{userId}";
|
||||||
|
private readonly IDatabase _redisDb = redis.GetDatabase();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 登录信息
|
/// 登录信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="loginItem"></param>
|
/// <param name="loginItem"></param>
|
||||||
|
/// <param name="expireTime"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string Login(SimApiLoginItem loginItem, string? token = null)
|
public string Login(SimApiLoginItem loginItem, TimeSpan? expireTime = null, string? token = null)
|
||||||
{
|
{
|
||||||
|
expireTime ??= TimeSpan.FromDays(7);
|
||||||
token ??= Guid.NewGuid().ToString();
|
token ??= Guid.NewGuid().ToString();
|
||||||
cache.SetString(token, JsonSerializer.Serialize(loginItem));
|
var cacheKey = TokenCacheKey.Replace("{token}", token);
|
||||||
|
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
|
||||||
|
_redisDb.SetAdd(setCacheKey, token);
|
||||||
|
cache.SetString(cacheKey, SimApiUtil.Json(loginItem),
|
||||||
|
new DistributedCacheEntryOptions
|
||||||
|
{
|
||||||
|
SlidingExpiration = expireTime
|
||||||
|
});
|
||||||
|
_redisDb.KeyExpire(setCacheKey, expireTime.Value);
|
||||||
|
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,10 +47,15 @@ public class SimApiAuth(IDistributedCache cache)
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string Update(SimApiLoginItem loginItem, string token)
|
public string Update(SimApiLoginItem loginItem, string token)
|
||||||
{
|
{
|
||||||
cache.SetString(token, JsonSerializer.Serialize(loginItem));
|
var cacheKey = TokenCacheKey.Replace("{token}", token);
|
||||||
|
cache.SetString(cacheKey, SimApiUtil.Json(loginItem));
|
||||||
|
var ttl = _redisDb.KeyTimeToLive(cacheKey);
|
||||||
|
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
|
||||||
|
_redisDb.KeyExpire(setCacheKey, ttl);
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取登陆信息
|
/// 获取登陆信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -42,19 +63,82 @@ public class SimApiAuth(IDistributedCache cache)
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public SimApiLoginItem? GetLogin(string token)
|
public SimApiLoginItem? GetLogin(string token)
|
||||||
{
|
{
|
||||||
var login = cache.GetString(token);
|
var cacheKey = TokenCacheKey.Replace("{token}", token);
|
||||||
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : null;
|
var login = cache.GetString(cacheKey);
|
||||||
|
var resp = login != null ? SimApiUtil.FromJson<SimApiLoginItem>(login) : null;
|
||||||
|
if (resp != null)
|
||||||
|
{
|
||||||
|
var ttl = _redisDb.KeyTimeToLive(cacheKey);
|
||||||
|
var setCacheKey = TokenSetCacheKey.Replace("{userId}", resp.Id);
|
||||||
|
_redisDb.KeyExpire(setCacheKey, ttl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取所有的登录token
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public SimApiLoginItem[] GetAllLogins(string userId)
|
||||||
|
{
|
||||||
|
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
|
||||||
|
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
|
||||||
|
var resp = new List<SimApiLoginItem>();
|
||||||
|
foreach (var login in allLogins)
|
||||||
|
{
|
||||||
|
if (login != null)
|
||||||
|
{
|
||||||
|
var item = GetLogin(login);
|
||||||
|
if (item != null)
|
||||||
|
{
|
||||||
|
resp.Add(item);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_redisDb.SetRemove(setCacheKey, login);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 退出所有登录
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
public void LogoutAll(string userId)
|
||||||
|
{
|
||||||
|
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
|
||||||
|
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
|
||||||
|
foreach (var login in allLogins)
|
||||||
|
{
|
||||||
|
if (login != null)
|
||||||
|
{
|
||||||
|
var cacheKey = TokenCacheKey.Replace("{token}", login);
|
||||||
|
cache.Remove(cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_redisDb.KeyDelete(setCacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 退出登陆
|
/// 退出登陆
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="uuid">登陆标识</param>
|
/// <param name="token">登陆标识</param>
|
||||||
public void Logout(string uuid)
|
public void Logout(string token)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(uuid))
|
var item = GetLogin(token);
|
||||||
|
if (item != null)
|
||||||
{
|
{
|
||||||
cache.Remove(uuid);
|
var setCacheKey = TokenSetCacheKey.Replace("{userId}", item.Id);
|
||||||
|
_redisDb.SetRemove(setCacheKey, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var cacheKey = TokenCacheKey.Replace("{token}", token);
|
||||||
|
cache.Remove(cacheKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+40
-3
@@ -7,8 +7,15 @@ public class SimApiCache(IDistributedCache cache)
|
|||||||
{
|
{
|
||||||
private const string Prefix = "SimApi:Cache:";
|
private const string Prefix = "SimApi:Cache:";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置缓存 (值不能为null)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <param name="value"></param>
|
||||||
|
/// <param name="options"></param>
|
||||||
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
|
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
|
||||||
{
|
{
|
||||||
|
SimApiError.ErrorWhenNull(value, 400, "缓存值不能为null");
|
||||||
if (options is not null)
|
if (options is not null)
|
||||||
{
|
{
|
||||||
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
|
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
|
||||||
@@ -19,14 +26,44 @@ public class SimApiCache(IDistributedCache cache)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public string? Get(string key)
|
/// <summary>
|
||||||
|
/// 移除缓存
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
public void Remove(string key)
|
||||||
{
|
{
|
||||||
return cache.GetString(Prefix + key);
|
cache.Remove(Prefix + key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 缓存Key是否存在
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool HasKey(string key)
|
||||||
|
{
|
||||||
|
return Get<string>(key) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取string类型缓存
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string? Get(string key)
|
||||||
|
{
|
||||||
|
return Get<string>(Prefix + key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取特定类型缓存
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
public T? Get<T>(string key)
|
public T? Get<T>(string key)
|
||||||
{
|
{
|
||||||
var data = cache.GetString(Prefix + key);
|
var data = cache.GetString(Prefix + key);
|
||||||
return data == null ? default : JsonSerializer.Deserialize<T>(data);
|
return data == null ? default : SimApiUtil.FromJson<T>(data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public static class SimApiError
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 错误返回
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="code">错误代码</param>
|
||||||
|
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[DoesNotReturn]
|
||||||
|
public static void Error(int code = 500, string message = "")
|
||||||
|
{
|
||||||
|
throw new SimApiException(code, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition">检测条件</param>
|
||||||
|
/// <param name="code">错误代码</param>
|
||||||
|
/// <param name="message">错误描述</param>
|
||||||
|
public static void ErrorWhen([DoesNotReturnIf(true)] bool condition, int code = 400,
|
||||||
|
string message = "")
|
||||||
|
{
|
||||||
|
if (condition)
|
||||||
|
{
|
||||||
|
Error(code, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition">检测条件</param>
|
||||||
|
/// <param name="code">错误代码</param>
|
||||||
|
/// <param name="message">错误描述</param>
|
||||||
|
public static void ErrorWhenTrue([DoesNotReturnIf(true)] bool condition, int code = 400,
|
||||||
|
string message = "")
|
||||||
|
{
|
||||||
|
ErrorWhen(condition, code, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 如果condition是false 报错
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition"></param>
|
||||||
|
/// <param name="code"></param>
|
||||||
|
/// <param name="message"></param>
|
||||||
|
public static void ErrorWhenFalse([DoesNotReturnIf(false)] bool condition, int code = 400,
|
||||||
|
string message = "")
|
||||||
|
{
|
||||||
|
ErrorWhen(!condition, code, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检测给定的变量是否为NUll
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition">检测条件</param>
|
||||||
|
/// <param name="code">错误代码</param>
|
||||||
|
/// <param name="message">错误描述</param>
|
||||||
|
public static void ErrorWhenNull([NotNull] object? condition, int code = 404,
|
||||||
|
string message = "请求的资源不存在")
|
||||||
|
{
|
||||||
|
ErrorWhen(condition == null, code, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,15 +8,28 @@ using SimApi.Exceptions;
|
|||||||
|
|
||||||
namespace SimApi.Helpers;
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
|
public class SimApiHttpClient
|
||||||
{
|
{
|
||||||
public string Server { get; init; } = string.Empty;
|
public required string Server { get; init; }
|
||||||
|
public required string AppId { get; init; }
|
||||||
|
|
||||||
|
public required string AppKey { get; init; }
|
||||||
|
|
||||||
|
public bool Debug { get; init; } = false;
|
||||||
public string SignName { get; init; } = "sign";
|
public string SignName { get; init; } = "sign";
|
||||||
public string TimestampName { get; init; } = "timestamp";
|
public string TimestampName { get; init; } = "timestamp";
|
||||||
public string NonceName { get; init; } = "nonce";
|
public string NonceName { get; init; } = "nonce";
|
||||||
public string? AppIdName { get; init; } = "appId";
|
public string? AppIdName { get; init; } = "appId";
|
||||||
public string[] SignFields { get; init; } = [];
|
public string[] SignFields { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发起签名请求
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="url"></param>
|
||||||
|
/// <param name="body"></param>
|
||||||
|
/// <param name="queries"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
|
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
|
||||||
{
|
{
|
||||||
url = Server + url;
|
url = Server + url;
|
||||||
@@ -24,11 +37,11 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
|
|||||||
(current, signField) => current + $"{signField}={queries?[signField]}&");
|
(current, signField) => current + $"{signField}={queries?[signField]}&");
|
||||||
if (!string.IsNullOrEmpty(AppIdName))
|
if (!string.IsNullOrEmpty(AppIdName))
|
||||||
{
|
{
|
||||||
queryUrl += $"{AppIdName}={appId}&";
|
queryUrl += $"{AppIdName}={AppId}&";
|
||||||
}
|
}
|
||||||
|
|
||||||
queryUrl += $"{TimestampName}={(int)SimApiUtil.TimestampNow}&{NonceName}={Guid.NewGuid()}";
|
queryUrl += $"{TimestampName}={(int)SimApiUtil.TimestampNow}&{NonceName}={Guid.NewGuid()}";
|
||||||
var signStr = $"{queryUrl}&{appKey}";
|
var signStr = $"{queryUrl}&{AppKey}";
|
||||||
var path = $"{url}?{queryUrl}&{SignName}={SimApiUtil.Md5(signStr)}";
|
var path = $"{url}?{queryUrl}&{SignName}={SimApiUtil.Md5(signStr)}";
|
||||||
|
|
||||||
if (queries != null)
|
if (queries != null)
|
||||||
@@ -40,40 +53,63 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
|
|||||||
return Query<T>(path, body);
|
return Query<T>(path, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发起AES加密请求
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="url"></param>
|
||||||
|
/// <param name="body"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
public T? AesQuery<T>(string url, object body)
|
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}";
|
||||||
}
|
}
|
||||||
|
|
||||||
var req = new SimApiOneFieldRequest<string>
|
var req = new SimApiOneFieldRequest<string>
|
||||||
{
|
{
|
||||||
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
|
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
|
||||||
};
|
};
|
||||||
return Query<T>(url, req);
|
return Query<T>(url, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发起AES加密以及签名请求
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="url"></param>
|
||||||
|
/// <param name="body"></param>
|
||||||
|
/// <param name="queries"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
public T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
public T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
||||||
{
|
{
|
||||||
var req = new SimApiOneFieldRequest<string>
|
var req = new SimApiOneFieldRequest<string>
|
||||||
{
|
{
|
||||||
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
|
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
|
||||||
};
|
};
|
||||||
return SignQuery<T>(url, req, queries);
|
return SignQuery<T>(url, req, queries);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发起请求
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="url"></param>
|
||||||
|
/// <param name="req"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
/// <exception cref="SimApiException"></exception>
|
||||||
private T? Query<T>(string url, object? req)
|
private T? Query<T>(string url, object? req)
|
||||||
{
|
{
|
||||||
var http = new HttpClient();
|
var http = new HttpClient();
|
||||||
if (debug)
|
if (Debug)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
|
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
var resp = http.PostAsJsonAsync(url, req).Result;
|
var resp = http.PostAsJsonAsync(url, req).Result;
|
||||||
if (debug)
|
if (Debug)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
|
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Net.Mail;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@@ -94,6 +95,25 @@ public static class SimApiUtil
|
|||||||
return regex.IsMatch(cell);
|
return regex.IsMatch(cell);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断是否是Email地址
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="email"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static bool CheckEmail(string email)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var m = new MailAddress(email);
|
||||||
|
return m.Address == email;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// MD5加密字符串
|
/// MD5加密字符串
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -131,6 +151,51 @@ public static class SimApiUtil
|
|||||||
return sb.ToString();
|
return sb.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 字符串Base64编码
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="str"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string Base64Encode(string str)
|
||||||
|
{
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(str);
|
||||||
|
return Convert.ToBase64String(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从Base64中解码字符串
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="base64Str"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string Base64Decode(string base64Str)
|
||||||
|
{
|
||||||
|
var bytes = Convert.FromBase64String(base64Str);
|
||||||
|
return Encoding.UTF8.GetString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 把对象Base64编码
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="obj"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string Base64Encode(object obj)
|
||||||
|
{
|
||||||
|
var json = Json(obj);
|
||||||
|
return Base64Encode(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从Base64中解析对象
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="base64Str"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static T? Base64Decode<T>(string base64Str)
|
||||||
|
{
|
||||||
|
var json = Base64Decode(base64Str);
|
||||||
|
return FromJson<T>(json);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将XML字符串序列化为对象
|
/// 将XML字符串序列化为对象
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -154,6 +219,17 @@ public static class SimApiUtil
|
|||||||
return JsonSerializer.Serialize(obj, JsonOption);
|
return JsonSerializer.Serialize(obj, JsonOption);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将JSON解析为对象(控制台输出中文不会被编码)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="jsonString"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static T? FromJson<T>(string jsonString)
|
||||||
|
{
|
||||||
|
return JsonSerializer.Deserialize<T>(jsonString, JsonOption);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 分页
|
/// 分页
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using SimApi.Communications;
|
||||||
|
|
||||||
|
namespace SimApi.Interfaces;
|
||||||
|
|
||||||
|
public interface ISimApiAuthChecker
|
||||||
|
{
|
||||||
|
public void Run(SimApiLoginItem loginItem, string token);
|
||||||
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
using System.Text.Json;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
|
||||||
using SimApi.Communications;
|
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Middlewares;
|
namespace SimApi.Middlewares;
|
||||||
@@ -12,20 +10,20 @@ namespace SimApi.Middlewares;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiAuthMiddleware(RequestDelegate next)
|
public class SimApiAuthMiddleware(RequestDelegate next)
|
||||||
{
|
{
|
||||||
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
|
public Task Invoke(HttpContext httpContext, SimApiAuth auth)
|
||||||
{
|
{
|
||||||
string? token = null;
|
var token =
|
||||||
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
|
httpContext.Request.Headers["Token"].FirstOrDefault()
|
||||||
{
|
?? httpContext.Request.Query["token"].FirstOrDefault();
|
||||||
token = header;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(token)) return next(httpContext);
|
if (string.IsNullOrEmpty(token)) return next(httpContext);
|
||||||
var login = auth.GetLogin(token);
|
var login = auth.GetLogin(token);
|
||||||
if (login != null)
|
if (login != null)
|
||||||
{
|
{
|
||||||
|
httpContext.Items.Add("LoginToken", token);
|
||||||
httpContext.Items.Add("LoginInfo", login);
|
httpContext.Items.Add("LoginInfo", login);
|
||||||
}
|
}
|
||||||
|
|
||||||
return next(httpContext);
|
return next(httpContext);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
@@ -20,7 +19,6 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
context.Response.Headers["Query-Id"] = header;
|
context.Response.Headers["Query-Id"] = header;
|
||||||
}
|
}
|
||||||
|
|
||||||
SimApiBaseResponse response;
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await next(context);
|
await next(context);
|
||||||
@@ -31,39 +29,58 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
case 200:
|
case 200:
|
||||||
case 301:
|
case 301:
|
||||||
case 302:
|
case 302:
|
||||||
break;
|
|
||||||
case 404:
|
case 404:
|
||||||
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
break;
|
||||||
|
// case 404:
|
||||||
|
// throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
||||||
default:
|
default:
|
||||||
throw new SimApiException(context.Response.StatusCode);
|
throw new SimApiException(context.Response.StatusCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (SimApiException ex)
|
|
||||||
{
|
|
||||||
response = string.IsNullOrEmpty(ex.Message)
|
|
||||||
? new SimApiBaseResponse(ex.Code)
|
|
||||||
: new SimApiBaseResponse(ex.Code, ex.Message);
|
|
||||||
ErrorResponse(context, response);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
log.LogError("{Msg}", ex.Message);
|
// 解包异步异常
|
||||||
log.LogError("{Msg}", ex.StackTrace);
|
ex = UnwrapAggregateException(ex);
|
||||||
response = new SimApiBaseResponse(500, ex.Message);
|
SimApiBaseResponse response;
|
||||||
ErrorResponse(context, 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>
|
private static Exception UnwrapAggregateException(Exception ex)
|
||||||
/// 异常抛出错误
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
/// <param name="response"></param>
|
|
||||||
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
|
||||||
{
|
{
|
||||||
|
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.StatusCode = 200;
|
||||||
context.Response.Headers.Append("Content-Type", "application/json");
|
context.Response.ContentType = "application/json";
|
||||||
context.Response.WriteAsync(response.ToString()).Wait();
|
context.Response.ContentLength = null; // 清除可能已设置的 Content-Length
|
||||||
|
await context.Response.WriteAsync(response.ToString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.Middlewares;
|
||||||
|
|
||||||
|
public class SimApiGateAuthMiddleware(RequestDelegate next, ILogger<SimApiGateAuthMiddleware> logger)
|
||||||
|
{
|
||||||
|
public Task Invoke(HttpContext httpContext, SimApiOptions simApiOptions)
|
||||||
|
{
|
||||||
|
if (httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Auth", out var auth) &&
|
||||||
|
httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Time", out var time) &&
|
||||||
|
httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Sign", out var sign))
|
||||||
|
{
|
||||||
|
var signStr =
|
||||||
|
$"appId={simApiOptions.SimApiGateAuthOptions.AppId}&auth={auth}&time={time}&appKey={simApiOptions.SimApiGateAuthOptions.AppKey}";
|
||||||
|
logger.LogDebug($"签名字符串 => {signStr}");
|
||||||
|
if (SimApiUtil.Md5(signStr) == sign && !string.IsNullOrEmpty(auth))
|
||||||
|
{
|
||||||
|
var login = SimApiUtil.Base64Decode<SimApiLoginItem>(auth!);
|
||||||
|
httpContext.Items.Add("LoginInfo", login);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logger.LogDebug("签名不匹配");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return next(httpContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,7 +30,7 @@ public class AesBodyModelBinder : IModelBinder
|
|||||||
SimApiOneFieldRequest<string>? aesRequest;
|
SimApiOneFieldRequest<string>? aesRequest;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
aesRequest = JsonSerializer.Deserialize<SimApiOneFieldRequest<string>>(requestBody, SimApiUtil.JsonOption);
|
aesRequest = SimApiUtil.FromJson<SimApiOneFieldRequest<string>>(requestBody);
|
||||||
}
|
}
|
||||||
catch (JsonException ex)
|
catch (JsonException ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Library</OutputType>
|
<OutputType>Library</OutputType>
|
||||||
<PackOnBuild>true</PackOnBuild>
|
<PackOnBuild>true</PackOnBuild>
|
||||||
@@ -12,10 +11,6 @@
|
|||||||
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
|
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
|
||||||
<Folder Include="Communications\"/>
|
|
||||||
<Folder Include="Exceptions\"/>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
|
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
|
||||||
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
|
<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.Annotations" Version="10.1.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
|
||||||
<Content Include=".github\workflows\nuget-publish.yml" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ProjectExtensions>
|
|
||||||
<MonoDevelop>
|
|
||||||
<Properties>
|
|
||||||
<Policies>
|
|
||||||
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical"/>
|
|
||||||
</Policies>
|
|
||||||
</Properties>
|
|
||||||
</MonoDevelop>
|
|
||||||
</ProjectExtensions>
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
+43
-21
@@ -1,5 +1,4 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
@@ -19,8 +18,10 @@ using Microsoft.Extensions.Logging;
|
|||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.CoceSdk;
|
using SimApi.CoceSdk;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Interfaces;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
using SimApi.SwaggerFilters;
|
using SimApi.SwaggerFilters;
|
||||||
|
using StackExchange.Redis;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
@@ -38,6 +39,8 @@ public static class SimApiExtensions
|
|||||||
if (simApiOptions.RedisConfiguration != null)
|
if (simApiOptions.RedisConfiguration != null)
|
||||||
{
|
{
|
||||||
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
|
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
|
||||||
|
builder.AddSingleton<IConnectionMultiplexer>(_ =>
|
||||||
|
ConnectionMultiplexer.Connect(simApiOptions.RedisConfiguration));
|
||||||
builder.AddSingleton<SimApiCache>();
|
builder.AddSingleton<SimApiCache>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,6 +64,20 @@ public static class SimApiExtensions
|
|||||||
builder.AddSingleton<CoceApp>();
|
builder.AddSingleton<CoceApp>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var simApiAuthChecker = typeof(ISimApiAuthChecker);
|
||||||
|
var stackTrace = new StackTrace();
|
||||||
|
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
||||||
|
var callerAssembly = callingMethod?.DeclaringType?.Assembly;
|
||||||
|
var callerTypes = callerAssembly?.GetTypes() ?? [];
|
||||||
|
|
||||||
|
foreach (var type in callerTypes)
|
||||||
|
{
|
||||||
|
if (type is { IsClass: true, IsAbstract: false } && simApiAuthChecker.IsAssignableFrom(type))
|
||||||
|
{
|
||||||
|
builder.AddScoped(simApiAuthChecker, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableJob)
|
if (simApiOptions.EnableJob)
|
||||||
{
|
{
|
||||||
builder.AddHangfire(x =>
|
builder.AddHangfire(x =>
|
||||||
@@ -94,12 +111,7 @@ public static class SimApiExtensions
|
|||||||
if (simApiOptions.EnableSynapse)
|
if (simApiOptions.EnableSynapse)
|
||||||
{
|
{
|
||||||
builder.AddSingleton<Synapse>();
|
builder.AddSingleton<Synapse>();
|
||||||
//自动依赖注入
|
foreach (var type in callerTypes)
|
||||||
var stackTrace = new StackTrace();
|
|
||||||
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
|
||||||
var assembly = callingMethod?.DeclaringType?.Assembly;
|
|
||||||
var types = assembly?.GetTypes() ?? [];
|
|
||||||
foreach (var type in types)
|
|
||||||
{
|
{
|
||||||
var methodsWithSynapse = type.GetMethods()
|
var methodsWithSynapse = type.GetMethods()
|
||||||
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
|
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
|
||||||
@@ -136,14 +148,14 @@ public static class SimApiExtensions
|
|||||||
if (t.IsArray)
|
if (t.IsArray)
|
||||||
{
|
{
|
||||||
var elementType = t.GetElementType();
|
var elementType = t.GetElementType();
|
||||||
return $"{GetSimpleTypeName(elementType, depth + 1)}[]";
|
return $"{GetSimpleTypeName(elementType!, depth + 1)}[]";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理可空类型
|
// 处理可空类型
|
||||||
if (Nullable.GetUnderlyingType(t) != null)
|
if (Nullable.GetUnderlyingType(t) != null)
|
||||||
{
|
{
|
||||||
var underlyingType = Nullable.GetUnderlyingType(t);
|
var underlyingType = Nullable.GetUnderlyingType(t);
|
||||||
return GetSimpleTypeName(underlyingType, depth + 1);
|
return GetSimpleTypeName(underlyingType!, depth + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理泛型类型(递归解析嵌套泛型)
|
// 处理泛型类型(递归解析嵌套泛型)
|
||||||
@@ -392,22 +404,32 @@ public static class SimApiExtensions
|
|||||||
builder.MapControllers();
|
builder.MapControllers();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var checkers = builder.Services.CreateScope().ServiceProvider.GetServices<ISimApiAuthChecker>().ToArray();
|
||||||
|
if (checkers.Length != 0)
|
||||||
|
{
|
||||||
|
var msg = checkers.Aggregate("开始配置SimApiAuthChecker...",
|
||||||
|
(current, checker) => current + $"\n|- {checker.GetType().FullName}");
|
||||||
|
logger.LogInformation(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.EnableSimApiGateAuth)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置SimApiGateAuth...");
|
||||||
|
if (string.IsNullOrEmpty(options.SimApiGateAuthOptions.AppId) ||
|
||||||
|
string.IsNullOrEmpty(options.SimApiGateAuthOptions.AppKey))
|
||||||
|
{
|
||||||
|
logger.LogCritical("必须配置Gate的AppId和AppKey才能启用SimApiGateAuth");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
builder.UseMiddleware<SimApiGateAuthMiddleware>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiAuth)
|
if (options.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiAuth...");
|
logger.LogInformation("开始配置SimApiAuth...");
|
||||||
builder.UseMiddleware<SimApiAuthMiddleware>();
|
builder.UseMiddleware<SimApiAuthMiddleware>();
|
||||||
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
|
|
||||||
defaults: new
|
|
||||||
{
|
|
||||||
controller = "SimApiAuth",
|
|
||||||
action = "UserInfo"
|
|
||||||
});
|
|
||||||
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
|
|
||||||
defaults: new
|
|
||||||
{
|
|
||||||
controller = "SimApiAuth",
|
|
||||||
action = "CheckLogin"
|
|
||||||
});
|
|
||||||
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
|
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
|
||||||
defaults: new
|
defaults: new
|
||||||
{
|
{
|
||||||
|
|||||||
-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;
|
.GetCustomAttribute<AesBodyAttribute>() != null;
|
||||||
if (!hasAesBodyAttr) continue;
|
if (!hasAesBodyAttr) continue;
|
||||||
// 1. 移除默认的 Query 参数描述(如果存在)
|
// 1. 移除默认的 Query 参数描述(如果存在)
|
||||||
var queryParam = operation.Parameters
|
var queryParam = operation.Parameters!
|
||||||
.FirstOrDefault(p => p.Name == parameter.Name);
|
.FirstOrDefault(p => p.Name == parameter.Name);
|
||||||
if (queryParam != null)
|
if (queryParam != null)
|
||||||
{
|
{
|
||||||
operation.Parameters.Remove(queryParam);
|
operation.Parameters!.Remove(queryParam);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 添加 Body 参数描述
|
// 2. 添加 Body 参数描述
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ public class GlobalDynamicObjectSchemaFilter : ISchemaFilter
|
|||||||
{
|
{
|
||||||
if (!IsDynamicObjectType(context.Type)) return;
|
if (!IsDynamicObjectType(context.Type)) return;
|
||||||
var oaSchema = schema as OpenApiSchema;
|
var oaSchema = schema as OpenApiSchema;
|
||||||
oaSchema.AdditionalPropertiesAllowed = true;
|
oaSchema!.AdditionalPropertiesAllowed = true;
|
||||||
oaSchema.AdditionalProperties = new OpenApiSchema
|
oaSchema.AdditionalProperties = new OpenApiSchema
|
||||||
{
|
{
|
||||||
Type = JsonSchemaType.Object, // 表示 value 可以是任意类型(兼容所有类型)
|
Type = JsonSchemaType.Object, // 表示 value 可以是任意类型(兼容所有类型)
|
||||||
|
|||||||
@@ -10,16 +10,16 @@ public class RemoveEmptyTagsFilter : IDocumentFilter
|
|||||||
{
|
{
|
||||||
// 步骤1:收集所有有接口的 Tag 名称
|
// 步骤1:收集所有有接口的 Tag 名称
|
||||||
var tagsWithOperations = swaggerDoc.Paths.Values
|
var tagsWithOperations = swaggerDoc.Paths.Values
|
||||||
.SelectMany(path => path.Operations.Values)
|
.SelectMany(path => path.Operations!.Values)
|
||||||
.SelectMany(op => op.Tags.Select(t => t.Name))
|
.SelectMany(op => op.Tags!.Select(t => t.Name))
|
||||||
.Distinct()
|
.Distinct()
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
// 步骤2:移除无接口的空 Tag
|
// 步骤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)
|
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);
|
var schema = context.SchemaGenerator.GenerateSchema(wrappedType, context.SchemaRepository);
|
||||||
|
|
||||||
// 5. 替换 Swagger 文档中的响应类型(只保留 200 OK 的响应,匹配过滤器逻辑)
|
// 5. 替换 Swagger 文档中的响应类型(只保留 200 OK 的响应,匹配过滤器逻辑)
|
||||||
operation.Responses.Clear(); // 清除默认响应(如 200 返回原始类型)
|
operation.Responses!.Clear(); // 清除默认响应(如 200 返回原始类型)
|
||||||
operation.Responses.Add("200", new OpenApiResponse
|
operation.Responses.Add("200", new OpenApiResponse
|
||||||
{
|
{
|
||||||
Description = "请求成功",
|
Description = "请求成功",
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
paramJson = SimApiUtil.Json(param);
|
||||||
}
|
}
|
||||||
|
|
||||||
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
|
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
|
||||||
var message = new MqttApplicationMessageBuilder()
|
var message = new MqttApplicationMessageBuilder()
|
||||||
.WithTopic(topic)
|
.WithTopic(topic)
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
paramJson = SimApiUtil.Json(param);
|
||||||
}
|
}
|
||||||
|
|
||||||
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
|
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
|
||||||
@@ -73,7 +73,7 @@ public partial class Synapse
|
|||||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
|
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
|
||||||
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
|
messageId, Options.AppName, action, app, paramJson, SimApiUtil.Json(headers));
|
||||||
|
|
||||||
string response;
|
string response;
|
||||||
try
|
try
|
||||||
@@ -88,13 +88,12 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
|
response = SimApiUtil.Json(new SimApiBaseResponse(502, "timeout"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"),
|
response = SimApiUtil.Json(new SimApiBaseResponse(500, "Synapse RPC Client Error"));
|
||||||
SimApiUtil.JsonOption);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ using MQTTnet.Protocol;
|
|||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
var returnJson = SimApiUtil.Json(res);
|
||||||
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
|
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
|
||||||
var message = new MqttApplicationMessageBuilder()
|
var message = new MqttApplicationMessageBuilder()
|
||||||
.WithTopic(reply)
|
.WithTopic(reply)
|
||||||
|
|||||||
+1
-1
@@ -101,7 +101,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
var data = FireRpc(appName, method, param, headers, timeout);
|
var data = FireRpc(appName, method, param, headers, timeout);
|
||||||
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
res = SimApiUtil.FromJson<SimApiBaseResponse<T>>(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (res as SimApiBaseResponse<T>)!;
|
return (res as SimApiBaseResponse<T>)!;
|
||||||
|
|||||||
Reference in New Issue
Block a user