Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
106d3eec19 | ||
|
|
a8c7a20a64 | ||
|
|
b6dbcd6cee | ||
|
|
b7775cbe6c | ||
|
|
28c6d53f38 | ||
|
|
ebceb0a260 | ||
|
|
162b92a415 | ||
|
|
a859986a93 | ||
|
|
e1c6694e18 | ||
|
|
566b1d190b | ||
|
|
eb8c9732bd | ||
|
|
c8b78ce86d | ||
|
|
b2ec94e957 | ||
|
|
a8439c174c | ||
|
|
81e166ad45 | ||
|
|
d50d32f032 | ||
|
|
8ad43526fc | ||
|
|
e2d30c031d | ||
|
|
9dc4ef7bce | ||
|
|
d5eb7fe081 | ||
|
|
b04a7c86d7 | ||
|
|
8759b593db | ||
|
|
5a46a026a7 |
@@ -9,16 +9,21 @@ jobs:
|
||||
publish:
|
||||
name: Publish Project to Nuget
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup .NET Core
|
||||
uses: actions/setup-dotnet@v1
|
||||
uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: "9.0.305"
|
||||
dotnet-version: "10.x.x"
|
||||
- name: NuGet login (OIDC → temp API key)
|
||||
uses: NuGet/login@v1
|
||||
id: login
|
||||
with:
|
||||
user: ${{ secrets.NUGET_USER }}
|
||||
- name: Publish
|
||||
run: |
|
||||
version=`git describe --tags`
|
||||
dotnet build --configuration release -p:Version=$version
|
||||
dotnet nuget push bin/release/Simcu.SimApi.$version.nupkg -k ${NUGET_APIKEY} -s https://www.nuget.org/api/v2/package
|
||||
env:
|
||||
NUGET_APIKEY: ${{ secrets.NUGET_APIKEY }}
|
||||
dotnet nuget push bin/release/Simcu.SimApi.$version.nupkg -k ${{steps.login.outputs.NUGET_API_KEY}} -s https://api.nuget.org/v3/index.json
|
||||
@@ -13,13 +13,13 @@ namespace SimApi.Attributes;
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public class SimApiAuthAttribute : ActionFilterAttribute
|
||||
{
|
||||
private string[] Types { get; }
|
||||
private string[]? Types { get; }
|
||||
|
||||
|
||||
//默认是user登录类型
|
||||
public SimApiAuthAttribute()
|
||||
{
|
||||
Types = new[] { "user" };
|
||||
Types = null;
|
||||
}
|
||||
|
||||
//只检测一种用户类型的快捷方式
|
||||
@@ -34,13 +34,6 @@ public class SimApiAuthAttribute : ActionFilterAttribute
|
||||
Types = types;
|
||||
}
|
||||
|
||||
//只检测一种用户类型的快捷方式
|
||||
public SimApiAuthAttribute(string type, string url)
|
||||
{
|
||||
Types = new[] { type };
|
||||
new HttpPostAttribute(url);
|
||||
}
|
||||
|
||||
public override void OnActionExecuting(ActionExecutingContext context)
|
||||
{
|
||||
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
|
||||
@@ -49,6 +42,8 @@ public class SimApiAuthAttribute : ActionFilterAttribute
|
||||
{
|
||||
throw new SimApiException(401);
|
||||
}
|
||||
|
||||
if (Types == null) return;
|
||||
//检测用户类型
|
||||
if (!Types.Intersect(loginInfo.Type).Any())
|
||||
{
|
||||
|
||||
@@ -12,13 +12,28 @@ public class SimApiDocAttribute : SwaggerOperationAttribute
|
||||
/// <summary>
|
||||
/// 定义接口说明
|
||||
/// </summary>
|
||||
/// <param name="tag">接口分组</param>
|
||||
/// <param name="tags">接口分组列表</param>
|
||||
/// <param name="name">接口名称</param>
|
||||
public SimApiDocAttribute(string tag, string name)
|
||||
/// <param name="description">接口描述</param>
|
||||
public SimApiDocAttribute(string[] tags, string name, string? description = null)
|
||||
{
|
||||
Tags = [tag];
|
||||
Tags = tags;
|
||||
Summary = name;
|
||||
if (description != null)
|
||||
{
|
||||
Description = description;
|
||||
}
|
||||
// Consumes = new[] {"application/json"};
|
||||
// Produces = new[] {"application/json"};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 定义接口说明
|
||||
/// </summary>
|
||||
/// <param name="tag">接口分组</param>
|
||||
/// <param name="name">接口名称</param>
|
||||
/// <param name="description">接口描述</param>
|
||||
public SimApiDocAttribute(string tag, string name, string? description = null) : this([tag], name, description)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using SimApi.Attributes;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Controllers;
|
||||
using SimApi.Helpers;
|
||||
using static SimApi.Helpers.SimApiError;
|
||||
|
||||
namespace SimApi.CoceSdk;
|
||||
|
||||
@@ -19,7 +20,7 @@ public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp)
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public SimApiBaseResponse<string> Login([FromBody] SimApiOneFieldRequest<string> request)
|
||||
public string Login([FromBody] SimApiOneFieldRequest<string> request)
|
||||
{
|
||||
var data = coce.GetLevelToken(request.Data!);
|
||||
ErrorWhenNull(data, 400);
|
||||
@@ -38,14 +39,14 @@ public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp)
|
||||
};
|
||||
var processor = sp.GetService<ICoceLoginProcessor>();
|
||||
processor?.Process(loginItem, groups.ToArray());
|
||||
return new SimApiBaseResponse<string>(auth.Login(loginItem));
|
||||
return auth.Login(loginItem);
|
||||
}
|
||||
|
||||
[HttpPost, SimApiAuth]
|
||||
public SimApiBaseResponse<GroupInfo[]> ListGroups()
|
||||
public GroupInfo[] ListGroups()
|
||||
{
|
||||
var levelToken = coce.GetToken(LoginInfo.Id!);
|
||||
var groups = coce.GetUserGroups(levelToken!)!;
|
||||
return new SimApiBaseResponse<GroupInfo[]>(groups.ToArray());
|
||||
return groups.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -46,23 +46,15 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态内容分页
|
||||
/// 分页内容返回
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
||||
public class PageResponse<T>
|
||||
{
|
||||
public T? List { get; set; }
|
||||
public int Page { get; set; } = 1;
|
||||
public int Count { get; set; } = 20;
|
||||
public int Total { get; set; }
|
||||
|
||||
public SimApiBasePageResponse(T list, int page, int count, int total) : this()
|
||||
{
|
||||
List = list;
|
||||
Page = page;
|
||||
Count = count;
|
||||
Total = total;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -29,11 +29,12 @@ public class SimApiJobOptions
|
||||
/// 设置为null 使用默认redis配置
|
||||
/// </summary>
|
||||
public int? Database { get; set; } = null;
|
||||
|
||||
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
||||
}
|
||||
|
||||
public class SimApiJobServerConfig()
|
||||
{
|
||||
public string[] Queues { get; set; } = ["default"];
|
||||
public int WorkerNum { get; set; } = 50;
|
||||
public int WorkerNum { get; set; } = 5;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SimApi.Attributes;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Helpers;
|
||||
|
||||
namespace SimApi.Controllers;
|
||||
|
||||
using static SimApiError;
|
||||
|
||||
public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
|
||||
{
|
||||
/// <summary>
|
||||
@@ -13,13 +14,10 @@ public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost, SimApiDoc("认证", "检测登陆")]
|
||||
public SimApiBaseResponse<string> CheckLogin()
|
||||
public string CheckLogin()
|
||||
{
|
||||
ErrorWhenNull(LoginInfo, 401, "未登录");
|
||||
return new SimApiBaseResponse<string>
|
||||
{
|
||||
Data = LoginInfo.Id
|
||||
};
|
||||
return LoginInfo.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -27,23 +25,15 @@ public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost, SimApiDoc("认证", "退出登陆")]
|
||||
public SimApiBaseResponse Logout()
|
||||
public void Logout()
|
||||
{
|
||||
string? token = null;
|
||||
|
||||
if (Request.Headers.TryGetValue("Token", out var value))
|
||||
{
|
||||
token = value;
|
||||
auth.Logout(value!);
|
||||
}
|
||||
|
||||
auth.Logout(token!);
|
||||
return new SimApiBaseResponse();
|
||||
}
|
||||
|
||||
|
||||
[HttpPost, SimApiAuth]
|
||||
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
||||
{
|
||||
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
||||
}
|
||||
[HttpPost, SimApiAuth, SimApiDoc("认证", "获取已登录用户信息")]
|
||||
public SimApiLoginItem UserInfo() => LoginInfo;
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Communications;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using System.Linq;
|
||||
using SimApi.Exceptions;
|
||||
using static SimApi.Helpers.SimApiError;
|
||||
|
||||
namespace SimApi.Controllers;
|
||||
|
||||
@@ -38,74 +37,4 @@ public class SimApiBaseController : Controller
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 错误返回
|
||||
/// </summary>
|
||||
/// <param name="code">错误代码</param>
|
||||
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
|
||||
/// <returns></returns>
|
||||
protected static void Error(int code = 500, string message = "")
|
||||
{
|
||||
throw new SimApiException(code, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||
/// </summary>
|
||||
/// <param name="condition">检测条件</param>
|
||||
/// <param name="code">错误代码</param>
|
||||
/// <param name="message">错误描述</param>
|
||||
protected static void ErrorWhen([DoesNotReturnIf(true)] bool condition, int code = 400, string message = "")
|
||||
{
|
||||
if (condition)
|
||||
{
|
||||
Error(code, message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||
/// </summary>
|
||||
/// <param name="condition">检测条件</param>
|
||||
/// <param name="code">错误代码</param>
|
||||
/// <param name="message">错误描述</param>
|
||||
protected static void ErrorWhenTrue([DoesNotReturnIf(true)] bool condition, int code = 400, string message = "")
|
||||
{
|
||||
ErrorWhen(condition, code, message);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 如果condition是false 报错
|
||||
/// </summary>
|
||||
/// <param name="condition"></param>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="message"></param>
|
||||
protected static void ErrorWhenFalse([DoesNotReturnIf(false)] bool condition, int code = 400, string message = "")
|
||||
{
|
||||
ErrorWhen(!condition, code, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测给定的变量是否为NUll
|
||||
/// </summary>
|
||||
/// <param name="condition">检测条件</param>
|
||||
/// <param name="code">错误代码</param>
|
||||
/// <param name="message">错误描述</param>
|
||||
protected static void ErrorWhenNull([NotNull] object? condition, int code = 404, string message = "请求的资源不存在")
|
||||
{
|
||||
ErrorWhen(condition == null, code, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上传文件
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected SimApiBaseResponse<string> UploadFile()
|
||||
{
|
||||
return new SimApiBaseResponse<string>();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Helpers;
|
||||
|
||||
namespace SimApi.Controllers;
|
||||
@@ -14,22 +13,19 @@ public class SimApiCommonController : SimApiBaseController
|
||||
/// <returns></returns>
|
||||
[HttpGet("exception/{code:int}")]
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
public SimApiBaseResponse ExceptionHandler(int code)
|
||||
public void ExceptionHandler(int code)
|
||||
{
|
||||
return new SimApiBaseResponse(code);
|
||||
SimApiError.Error(code);
|
||||
}
|
||||
|
||||
|
||||
[HttpPost, HttpGet]
|
||||
public SimApiBaseResponse<Dictionary<string, string>> Versions()
|
||||
public Dictionary<string, string> Versions()
|
||||
{
|
||||
return new SimApiBaseResponse<Dictionary<string, string>>()
|
||||
return new Dictionary<string, string>
|
||||
{
|
||||
Data = new Dictionary<string, string>
|
||||
{
|
||||
{ "SimApi", SimApiUtil.SimApiVersion },
|
||||
{ "App", SimApiUtil.AppVersion }
|
||||
}
|
||||
{ "SimApi", SimApiUtil.SimApiVersion },
|
||||
{ "App", SimApiUtil.AppVersion }
|
||||
};
|
||||
}
|
||||
}
|
||||
+39
-2
@@ -7,8 +7,15 @@ public class SimApiCache(IDistributedCache cache)
|
||||
{
|
||||
private const string Prefix = "SimApi:Cache:";
|
||||
|
||||
/// <summary>
|
||||
/// 设置缓存
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="options"></param>
|
||||
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
|
||||
{
|
||||
SimApiError.ErrorWhenNull(value, 400, "缓存值不能为null");
|
||||
if (options is not null)
|
||||
{
|
||||
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
|
||||
@@ -19,11 +26,41 @@ 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)
|
||||
{
|
||||
var data = cache.GetString(Prefix + key);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,30 @@ using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using SimApi.Communications;
|
||||
using SimApi.Exceptions;
|
||||
|
||||
namespace SimApi.Helpers;
|
||||
|
||||
public class SimApiHttpClient(string? appId, string appKey)
|
||||
public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
|
||||
{
|
||||
public string Server { get; init; } = string.Empty;
|
||||
public string SignName { get; init; } = "sign";
|
||||
public string TimestampName { get; init; } = "timestamp";
|
||||
public string NonceName { get; init; } = "nonce";
|
||||
public string? AppIdName { get; init; } = "appId";
|
||||
public string[] SignFields { get; init; } = [];
|
||||
|
||||
|
||||
public T? SignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
||||
/// <summary>
|
||||
/// 发起签名请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="body"></param>
|
||||
/// <param name="queries"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
|
||||
{
|
||||
url = Server + url;
|
||||
var queryUrl = SignFields.Aggregate(string.Empty,
|
||||
(current, signField) => current + $"{signField}={queries?[signField]}&");
|
||||
if (!string.IsNullOrEmpty(AppIdName))
|
||||
@@ -35,13 +45,19 @@ public class SimApiHttpClient(string? appId, string appKey)
|
||||
.Aggregate(path, (current, q) => current + $"&{q.Key}={q.Value}");
|
||||
}
|
||||
|
||||
var http = new HttpClient();
|
||||
var resp = http.PostAsJsonAsync(path, body).Result;
|
||||
return resp.Content.ReadFromJsonAsync<T>().Result;
|
||||
return Query<T>(path, body);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发起AES加密请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="body"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public T? AesQuery<T>(string url, object body)
|
||||
{
|
||||
url = Server + url;
|
||||
if (!string.IsNullOrEmpty(AppIdName))
|
||||
{
|
||||
url += $"?{AppIdName}={appId}";
|
||||
@@ -51,11 +67,17 @@ public class SimApiHttpClient(string? appId, string appKey)
|
||||
{
|
||||
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
|
||||
};
|
||||
var http = new HttpClient();
|
||||
var resp = http.PostAsJsonAsync(url, req).Result;
|
||||
return resp.Content.ReadFromJsonAsync<T>().Result;
|
||||
return Query<T>(url, req);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发起AES加密以及签名请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="body"></param>
|
||||
/// <param name="queries"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
||||
{
|
||||
var req = new SimApiOneFieldRequest<string>
|
||||
@@ -64,4 +86,35 @@ public class SimApiHttpClient(string? appId, string appKey)
|
||||
};
|
||||
return SignQuery<T>(url, req, queries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发起请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="req"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="SimApiException"></exception>
|
||||
private T? Query<T>(string url, object? req)
|
||||
{
|
||||
var http = new HttpClient();
|
||||
if (debug)
|
||||
{
|
||||
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
|
||||
}
|
||||
|
||||
var resp = http.PostAsJsonAsync(url, req).Result;
|
||||
if (debug)
|
||||
{
|
||||
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
|
||||
}
|
||||
|
||||
var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result;
|
||||
if (res == null)
|
||||
{
|
||||
throw new SimApiException(500, "请求发生错误");
|
||||
}
|
||||
|
||||
return res.Code != 200 ? throw new SimApiException(res.Code, res.Message) : res.Data;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using SimApi.Communications;
|
||||
@@ -20,7 +19,6 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
||||
context.Response.Headers["Query-Id"] = header;
|
||||
}
|
||||
|
||||
SimApiBaseResponse response;
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
@@ -39,31 +37,48 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SimApiException ex)
|
||||
{
|
||||
response = string.IsNullOrEmpty(ex.Message)
|
||||
? new SimApiBaseResponse(ex.Code)
|
||||
: new SimApiBaseResponse(ex.Code, ex.Message);
|
||||
ErrorResponse(context, response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
log.LogError("{Msg}", ex.Message);
|
||||
log.LogError("{Msg}", ex.StackTrace);
|
||||
response = new SimApiBaseResponse(500, ex.Message);
|
||||
ErrorResponse(context, response);
|
||||
// 解包异步异常
|
||||
ex = UnwrapAggregateException(ex);
|
||||
SimApiBaseResponse response;
|
||||
if (ex is SimApiException simEx)
|
||||
{
|
||||
response = string.IsNullOrEmpty(simEx.Message)
|
||||
? new SimApiBaseResponse(simEx.Code)
|
||||
: new SimApiBaseResponse(simEx.Code, simEx.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
log.LogError(ex, "服务器异常");
|
||||
response = new SimApiBaseResponse(500, "服务器错误");
|
||||
}
|
||||
|
||||
await ErrorResponseAsync(context, response);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异常抛出错误
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="response"></param>
|
||||
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
||||
private static Exception UnwrapAggregateException(Exception ex)
|
||||
{
|
||||
while (ex is AggregateException aggEx && aggEx.InnerException != null)
|
||||
{
|
||||
ex = aggEx.InnerException;
|
||||
}
|
||||
|
||||
return ex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步输出错误响应(修复异步异常捕获核心)
|
||||
/// </summary>
|
||||
private static async Task ErrorResponseAsync(HttpContext context, SimApiBaseResponse response)
|
||||
{
|
||||
// 响应已开始则直接返回,不修改
|
||||
if (context.Response.HasStarted)
|
||||
return;
|
||||
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "application/json");
|
||||
context.Response.WriteAsync(response.ToString()).Wait();
|
||||
context.Response.ContentType = "application/json";
|
||||
await context.Response.WriteAsync(response.ToString());
|
||||
}
|
||||
}
|
||||
+2
-16
@@ -1,5 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<PackOnBuild>true</PackOnBuild>
|
||||
@@ -12,10 +11,6 @@
|
||||
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="Communications\"/>
|
||||
<Folder Include="Exceptions\"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
|
||||
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
|
||||
@@ -23,16 +18,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.1" />
|
||||
<PackageReference Include="Minio" Version="7.0.0" />
|
||||
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.0.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.0.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.0" />
|
||||
</ItemGroup>
|
||||
<ProjectExtensions>
|
||||
<MonoDevelop>
|
||||
<Properties>
|
||||
<Policies>
|
||||
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical"/>
|
||||
</Policies>
|
||||
</Properties>
|
||||
</MonoDevelop>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
|
||||
+73
-4
@@ -123,11 +123,80 @@ public static class SimApiExtensions
|
||||
});
|
||||
}
|
||||
|
||||
x.CustomSchemaIds(type => type.FullName?.Replace("+", "."));
|
||||
x.CustomSchemaIds(type =>
|
||||
{
|
||||
// 递归解析类型名称(处理嵌套泛型/数组/可空 + 保证唯一性)
|
||||
string GetSimpleTypeName(Type t, int depth = 0)
|
||||
{
|
||||
// 防止无限递归
|
||||
if (depth > 5) return t.Name.Split('`')[0];
|
||||
|
||||
// 处理数组类型
|
||||
if (t.IsArray)
|
||||
{
|
||||
var elementType = t.GetElementType();
|
||||
return $"{GetSimpleTypeName(elementType!, depth + 1)}[]";
|
||||
}
|
||||
|
||||
// 处理可空类型
|
||||
if (Nullable.GetUnderlyingType(t) != null)
|
||||
{
|
||||
var underlyingType = Nullable.GetUnderlyingType(t);
|
||||
return GetSimpleTypeName(underlyingType!, depth + 1);
|
||||
}
|
||||
|
||||
// 处理泛型类型(递归解析嵌套泛型)
|
||||
if (t.IsGenericType)
|
||||
{
|
||||
var genericBaseName = t.GetGenericTypeDefinition().Name.Split('`')[0];
|
||||
var genericArgs = t.GetGenericArguments()
|
||||
.Select(arg => GetSimpleTypeName(arg, depth + 1))
|
||||
.Where(arg => !string.IsNullOrEmpty(arg))
|
||||
.ToArray();
|
||||
return $"{genericBaseName}<{string.Join(",", genericArgs)}>";
|
||||
}
|
||||
|
||||
// 处理基础类型(小写)
|
||||
if (t.IsPrimitive || t == typeof(string) || t == typeof(DateTime) || t == typeof(Guid))
|
||||
{
|
||||
return t.Name switch
|
||||
{
|
||||
"String" => "string",
|
||||
"Int32" => "int",
|
||||
"Int64" => "long",
|
||||
"Boolean" => "boolean",
|
||||
"DateTime" => "datetime",
|
||||
"Guid" => "guid",
|
||||
_ => t.Name.ToLower()
|
||||
};
|
||||
}
|
||||
|
||||
// 核心修复:生成唯一名称(处理嵌套类/同名不同类)
|
||||
var typeName = t.Name;
|
||||
|
||||
// 步骤1:处理嵌套类(如 ApplicationDto+ApplicationEditRequest → ApplicationDto_ApplicationEditRequest)
|
||||
if (t.DeclaringType != null)
|
||||
{
|
||||
typeName = $"{GetSimpleTypeName(t.DeclaringType)}.{typeName}";
|
||||
}
|
||||
|
||||
// 步骤2:(可选)处理同命名空间下的同名类(拼接命名空间前缀,避免全局重复)
|
||||
// 如需更严格的唯一性,取消注释下面这行
|
||||
// typeName = $"{t.Namespace?.Replace(".", "_")}_{typeName}";
|
||||
|
||||
return typeName;
|
||||
}
|
||||
|
||||
// 根调用:解析当前类型
|
||||
var uniqueSchemaId = GetSimpleTypeName(type);
|
||||
// 可选:移除特殊字符(如 $、+),避免 Swagger 解析问题
|
||||
return uniqueSchemaId.Replace("$", "").Replace("+", "_");
|
||||
});
|
||||
x.OperationFilter<SimApiResponseOperationFilter>();
|
||||
x.OperationFilter<SimApiSignOperationFilter>();
|
||||
x.OperationFilter<AesBodyOperationFilter>();
|
||||
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
|
||||
x.DocumentFilter<RemoveEmptyTagsFilter>();
|
||||
if (simApiOptions.EnableSimApiAuth)
|
||||
{
|
||||
x.OperationFilter<SimApiAuthOperationFilter>();
|
||||
@@ -157,11 +226,12 @@ public static class SimApiExtensions
|
||||
switch (auth)
|
||||
{
|
||||
case "SimApiAuth":
|
||||
x.AddSecurityDefinition("HeaderToken",
|
||||
x.AddSecurityDefinition("SimApiAuth",
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Name = "Token",
|
||||
In = ParameterLocation.Header
|
||||
In = ParameterLocation.Header,
|
||||
Type = SecuritySchemeType.ApiKey
|
||||
});
|
||||
break;
|
||||
case "ClientCredentials":
|
||||
@@ -392,7 +462,6 @@ public static class SimApiExtensions
|
||||
x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name);
|
||||
}
|
||||
|
||||
x.EnableValidator();
|
||||
x.SupportedSubmitMethods(docOptions.SupportedMethod);
|
||||
x.DisplayRequestDuration();
|
||||
});
|
||||
|
||||
@@ -22,11 +22,11 @@ public class AesBodyOperationFilter : IOperationFilter
|
||||
.GetCustomAttribute<AesBodyAttribute>() != null;
|
||||
if (!hasAesBodyAttr) continue;
|
||||
// 1. 移除默认的 Query 参数描述(如果存在)
|
||||
var queryParam = operation.Parameters
|
||||
var queryParam = operation.Parameters!
|
||||
.FirstOrDefault(p => p.Name == parameter.Name);
|
||||
if (queryParam != null)
|
||||
{
|
||||
operation.Parameters.Remove(queryParam);
|
||||
operation.Parameters!.Remove(queryParam);
|
||||
}
|
||||
|
||||
// 2. 添加 Body 参数描述
|
||||
|
||||
@@ -13,7 +13,7 @@ public class GlobalDynamicObjectSchemaFilter : ISchemaFilter
|
||||
{
|
||||
if (!IsDynamicObjectType(context.Type)) return;
|
||||
var oaSchema = schema as OpenApiSchema;
|
||||
oaSchema.AdditionalPropertiesAllowed = true;
|
||||
oaSchema!.AdditionalPropertiesAllowed = true;
|
||||
oaSchema.AdditionalProperties = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object, // 表示 value 可以是任意类型(兼容所有类型)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using System.Linq;
|
||||
|
||||
namespace SimApi.SwaggerFilters;
|
||||
|
||||
public class RemoveEmptyTagsFilter : IDocumentFilter
|
||||
{
|
||||
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
|
||||
{
|
||||
// 步骤1:收集所有有接口的 Tag 名称
|
||||
var tagsWithOperations = swaggerDoc.Paths.Values
|
||||
.SelectMany(path => path.Operations!.Values)
|
||||
.SelectMany(op => op.Tags!.Select(t => t.Name))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
// 步骤2:移除无接口的空 Tag
|
||||
var emptyTags = swaggerDoc.Tags!.Where(t => !tagsWithOperations.Contains(t.Name)).ToList();
|
||||
foreach (var tag in emptyTags)
|
||||
{
|
||||
swaggerDoc.Tags!.Remove(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,22 +19,10 @@ namespace SimApi.SwaggerFilters
|
||||
// 控制器上有 [SimApiAuth](继承到所有方法)
|
||||
context.MethodInfo.DeclaringType?.GetCustomAttributes<SimApiAuthAttribute>(true).Any() == true;
|
||||
if (!requiresAuth) return;
|
||||
|
||||
// 关键修复:正确构造 OpenApiSecuritySchemeReference(匹配键类型要求)
|
||||
var securitySchemeRef = new OpenApiSecuritySchemeReference(
|
||||
referenceId: "SimApiAuth", // 必须与 AddSecurityDefinition 的 ID 一致
|
||||
hostDocument: null,
|
||||
externalResource: null
|
||||
);
|
||||
|
||||
// 给 Security 赋值(确保键类型是 OpenApiSecuritySchemeReference)
|
||||
operation.Security ??= new List<OpenApiSecurityRequirement>();
|
||||
operation.Security.Add(new OpenApiSecurityRequirement
|
||||
operation.Security.Add(new OpenApiSecurityRequirement()
|
||||
{
|
||||
{
|
||||
securitySchemeRef,
|
||||
[]
|
||||
}
|
||||
{ new OpenApiSecuritySchemeReference("SimApiAuth", context.Document), [] }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class SimApiResponseOperationFilter : IOperationFilter
|
||||
var schema = context.SchemaGenerator.GenerateSchema(wrappedType, context.SchemaRepository);
|
||||
|
||||
// 5. 替换 Swagger 文档中的响应类型(只保留 200 OK 的响应,匹配过滤器逻辑)
|
||||
operation.Responses.Clear(); // 清除默认响应(如 200 返回原始类型)
|
||||
operation.Responses!.Clear(); // 清除默认响应(如 200 返回原始类型)
|
||||
operation.Responses.Add("200", new OpenApiResponse
|
||||
{
|
||||
Description = "请求成功",
|
||||
|
||||
Reference in New Issue
Block a user