Compare commits

...
15 Commits
Author SHA1 Message Date
xrain 04b2be1bb7 fix bug 2024-07-21 13:50:12 +08:00
xrain f78c3a0e0d fix fullurl 不抛出异常了 2024-07-10 06:35:19 +08:00
xrain 506704fd90 fix fullurl 不抛出异常了 2024-07-10 06:29:36 +08:00
xrain 786051ddbf update pkg 2024-07-10 03:30:09 +08:00
xrain d9ff4ae422 fix upload url 2024-07-10 01:18:18 +08:00
xrain 986b4e74e6 new upload 2024-07-10 00:52:51 +08:00
xrain 2257ba5b2a new feature 2024-06-27 04:38:04 +08:00
xrain c40f8d664d default exception edit 2024-04-23 12:27:36 +08:00
xrain a1f10b9c09 class 添加默认方法,支持老的代码 2024-04-16 06:57:56 +08:00
xrain 6ef7aca8ae 将record切换回class, 不再使用CST时间,使用DateTime.Now 2024-04-16 06:29:21 +08:00
xrain 4171756c54 新增 ErrorWhenTrue和ErrorWhenFalse 2024-03-26 10:06:17 +08:00
xrain c68cfa6192 fix simapiauth to singleton 2024-03-24 17:40:48 +08:00
xrain 8344567ac6 新增了一个获取登陆信息的方法 2024-03-24 17:31:22 +08:00
xrain 99b26d99f6 fix code 2024-03-23 07:30:24 +08:00
xrain cb291691d5 upgrade to c#12 2024-03-23 07:29:43 +08:00
25 changed files with 1212 additions and 1104 deletions
+4 -11
View File
@@ -5,8 +5,8 @@ using Microsoft.AspNetCore.Mvc.Filters;
using SimApi.Communications;
using SimApi.Exceptions;
namespace SimApi.Attributes
{
namespace SimApi.Attributes;
/// <summary>
/// 检测登录中间件
/// </summary>
@@ -19,10 +19,7 @@ namespace SimApi.Attributes
//默认是user登录类型
public SimApiAuthAttribute()
{
Types = new[]
{
"user"
};
Types = new[] { "user" };
}
//只检测一种用户类型的快捷方式
@@ -40,10 +37,7 @@ namespace SimApi.Attributes
//只检测一种用户类型的快捷方式
public SimApiAuthAttribute(string type, string url)
{
Types = new[]
{
type
};
Types = new[] { type };
new HttpPostAttribute(url);
}
@@ -62,4 +56,3 @@ namespace SimApi.Attributes
}
}
}
}
+2 -3
View File
@@ -1,8 +1,8 @@
using System;
using Swashbuckle.AspNetCore.Annotations;
namespace SimApi.Attributes
{
namespace SimApi.Attributes;
/// <summary>
/// 快捷自定义接口文档类
/// </summary>
@@ -22,4 +22,3 @@ namespace SimApi.Attributes
// Produces = new[] {"application/json"};
}
}
}
+20 -6
View File
@@ -1,23 +1,37 @@
namespace SimApi.Communications
{
using System.ComponentModel.DataAnnotations;
namespace SimApi.Communications;
/// <summary>
/// 只有ID的请求
/// </summary>
public record SimApiIdOnlyRequest(int Id);
public class SimApiIdOnlyRequest
{
[Required] public int Id { get; set; }
}
/// <summary>
/// 只有ID的请求(字符串)
/// </summary>
public record SimApiStringIdOnlyRequest(string Id);
public class SimApiStringIdOnlyRequest
{
[Required] public string Id { get; set; }
}
/// <summary>
/// 动态类型单字段请求
/// </summary>
/// <typeparam name="T"></typeparam>
public record SimApiOneFieldRequest<T>(T Data);
public class SimApiOneFieldRequest<T>
{
[Required] public T Data { get; set; }
}
/// <summary>
/// 基础分页请求
/// </summary>
public record SimApiBasePageRequest(int Page, int Count);
public class SimApiBasePageRequest
{
[Required] public int Page { get; set; }
[Required] public int Count { get; set; }
}
+37 -30
View File
@@ -2,42 +2,31 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SimApi.Communications
{
namespace SimApi.Communications;
/// <summary>
/// 基础相应
/// </summary>
public record SimApiBaseResponse(int Code = 200, string Message = "成功")
public class SimApiBaseResponse(int code = 200, string message = "成功")
{
public int Code { get; set; } = code;
public string Message { get; set; } = message;
/// <summary>
/// 默认错误代码对应提示信息
/// </summary>
private static readonly Dictionary<int, string> MsgBox = new()
{
{
200, "成功"
},
{
204, "没有数据"
},
{
400, "参数错误"
},
{
401, "需要登录"
},
{
403, "无权访问"
},
{
404, "接口不存在"
},
{
500, "服务器错误"
}
{ 200, "成功" },
{ 204, "没有数据" },
{ 400, "参数错误" },
{ 401, "需要登录" },
{ 403, "无权访问" },
{ 404, "接口不存在" },
{ 500, "服务器错误" }
};
public SimApiBaseResponse(int code) : this(code, MsgBox.ContainsKey(code) ? MsgBox[code] : "未知错误")
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误"))
{
}
@@ -63,14 +52,32 @@ namespace SimApi.Communications
/// 动态内容分页
/// </summary>
/// <typeparam name="T"></typeparam>
public record SimApiBasePageResponse<T>
(T List, int Page = 1, int Count = 1, int Total = 1, int Code = 200,
string Message = "成功") : SimApiBaseResponse(Code, Message);
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
{
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>
/// 动态Data返回
/// </summary>
/// <typeparam name="T"></typeparam>
public record SimApiBaseResponse<T>(T Data, int Code = 200, string Message = "成功") : SimApiBaseResponse(Code,
Message);
public class SimApiBaseResponse<T>() : SimApiBaseResponse
{
public T Data { get; set; }
public SimApiBaseResponse(T data) : this()
{
Data = data;
}
}
+5 -4
View File
@@ -1,7 +1,8 @@
namespace SimApi.Communications
{
using System.Collections.Generic;
namespace SimApi.Communications;
/// <summary>
/// 登录信息中间件
/// </summary>
public record SimApiLoginItem(string Id, string[] Type);
}
public record SimApiLoginItem(string Id, string[] Type,Dictionary<string,string> Meta = null);
+7 -5
View File
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using Swashbuckle.AspNetCore.SwaggerUI;
namespace SimApi.Configs
{
namespace SimApi.Configurations;
/// <summary>
/// 文档组配置
/// </summary>
@@ -31,9 +30,13 @@ namespace SimApi.Configs
public class SimApiAuthOption
{
public string[] Type { get; set; } = new[] { "SimApiAuth" };
public string Description { get; set; } = "认证服务器颁发的AccessToken";
public string AuthorizationUrl { get; set; }
public string TokenUrl { get; set; }
public Dictionary<string, string> Scopes { get; set; }
}
@@ -70,4 +73,3 @@ namespace SimApi.Configs
/// </summary>
public SubmitMethod[] SupportedMethod { get; set; } = new[] { SubmitMethod.Post };
}
}
+3 -4
View File
@@ -1,7 +1,7 @@
using System;
namespace SimApi.Configs
{
namespace SimApi.Configurations;
public class SimApiOptions
{
/// <summary>
@@ -11,7 +11,7 @@ namespace SimApi.Configs
public bool EnableCors { get; set; } = true;
/// <summary>
/// 启用SimapiAuth,一个简单的基于Header Token的认证方式。
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
/// default: false
/// </summary>
public bool EnableSimApiAuth { get; set; } = false;
@@ -90,4 +90,3 @@ namespace SimApi.Configs
options?.Invoke(SimApiStorageOptions);
}
}
}
+2 -3
View File
@@ -1,5 +1,5 @@
namespace SimApi.Configs
{
namespace SimApi.Configurations;
public class SimApiStorageOptions
{
/// <summary>
@@ -21,4 +21,3 @@ namespace SimApi.Configs
public string SecretKey { get; set; }
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
namespace SimApi.Configs;
namespace SimApi.Configurations;
public class SimApiSynapseOptions
{
+30 -8
View File
@@ -4,10 +4,9 @@ using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Linq;
using SimApi.Exceptions;
using SimApi.Attributes;
namespace SimApi.Controllers
{
namespace SimApi.Controllers;
/// <summary>
/// 基础控制器,所有控制器均继承本控制器
/// 1. 自动验证请求参数
@@ -51,12 +50,12 @@ namespace SimApi.Controllers
}
/// <summary>
/// 检测条件,根据条件返回报错
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhen(bool condition, int code = 500, string message = "")
protected static void ErrorWhen(bool condition, int code = 400, string message = "")
{
if (condition)
{
@@ -64,13 +63,37 @@ namespace SimApi.Controllers
}
}
/// <summary>
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenTrue(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(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(object condition, int code = 404, string message = "")
protected static void ErrorWhenNull(object condition, int code = 404, string message = "请求的资源不存在")
{
ErrorWhen(condition == null, code, message);
}
@@ -81,7 +104,6 @@ namespace SimApi.Controllers
/// <returns></returns>
protected SimApiBaseResponse<string> UploadFile()
{
return new SimApiBaseResponse<string>(null);
}
return new SimApiBaseResponse<string>();
}
}
+16 -16
View File
@@ -1,21 +1,13 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.Controllers
{
namespace SimApi.Controllers;
[ApiExplorerSettings(GroupName = "api")]
public class YYCommonController : SimApiBaseController
public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
{
private SimApiAuth Auth { get; }
public YYCommonController(SimApiAuth auth)
{
Auth = auth;
}
/// <summary>
/// 错误回馈页面
/// </summary>
@@ -36,7 +28,10 @@ namespace SimApi.Controllers
public SimApiBaseResponse<string> CheckLogin()
{
ErrorWhenNull(LoginInfo, 401);
return new SimApiBaseResponse<string>(LoginInfo.Id);
return new SimApiBaseResponse<string>
{
Data = LoginInfo.Id
};
}
/// <summary>
@@ -48,13 +43,18 @@ namespace SimApi.Controllers
{
string token = null;
if (Request.Headers.ContainsKey("Token"))
if (Request.Headers.TryGetValue("Token", out var value))
{
token = Request.Headers["Token"];
token = value;
}
Auth.Logout(token);
auth.Logout(token!);
return new SimApiBaseResponse();
}
[HttpPost("/logined"),SimApiAuth]
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
{
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
}
}
+5 -10
View File
@@ -1,16 +1,11 @@
using System;
namespace SimApi.Exceptions
{
namespace SimApi.Exceptions;
/// <summary>
/// Api错误捕获异常
/// </summary>
public class SimApiException : Exception
public class SimApiException(int code, string message = "") : Exception(message)
{
public int Code { get; }
public SimApiException(int code, string message = "") : base(message)
{
Code = code;
}
}
public int Code { get; } = code;
}
+43 -21
View File
@@ -1,34 +1,28 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
namespace SimApi.Helpers
{
namespace SimApi.Helpers;
/// <summary>
/// 认证助手
/// </summary>
public class SimApiAuth
public class SimApiAuth(IDistributedCache cache)
{
private IDistributedCache Cache { get; }
public SimApiAuth(IDistributedCache cache)
{
Cache = cache;
}
/// <summary>
/// 产生一个Token记录并返回Token
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <param name="meta"></param>
/// <param name="token"></param>
/// <returns></returns>
public string Login(string id, string type = "user", string token = null)
public string Login(string id, Dictionary<string, string>? meta = null, string type = "user", string? token = null)
{
return Login(id, new[]
{
type
}, token);
return Login(id, meta, new[] { type }, token);
}
/// <summary>
@@ -36,15 +30,44 @@ namespace SimApi.Helpers
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <param name="meta"></param>
/// <param name="uuid"></param>
/// <returns></returns>
public string Login(string id, string[] type, string uuid = null)
// ReSharper disable once MemberCanBePrivate.Global
public string Login(string id, Dictionary<string, string>? meta, string[] type, string? uuid = null)
{
uuid ??= Guid.NewGuid().ToString();
var loginItem = new SimApiLoginItem(id, type);
Cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
var loginItem = new SimApiLoginItem(id, type, meta);
cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
return uuid;
}
/// <summary>
/// 设置登录的Meta信息
/// </summary>
/// <param name="token"></param>
/// <param name="meta"></param>
/// <returns></returns>
public bool SetMeta(string token, Dictionary<string, string> meta)
{
var login = GetLogin(token);
if (login == null) { return false; }
var newLogin = new SimApiLoginItem(login.Id, login.Type, login.Meta);
cache.SetString(token,JsonSerializer.Serialize(newLogin));
return true;
}
/// <summary>
/// 获取登陆信息
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public SimApiLoginItem? GetLogin(string token)
{
var login = cache.GetString(token);
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : default;
}
/// <summary>
/// 退出登陆
/// </summary>
@@ -53,8 +76,7 @@ namespace SimApi.Helpers
{
if (!string.IsNullOrEmpty(uuid))
{
Cache.Remove(uuid);
}
cache.Remove(uuid);
}
}
}
+77 -13
View File
@@ -1,20 +1,23 @@
using System;
#nullable enable
using System;
using System.IO;
using Microsoft.AspNetCore.Http;
using Minio;
using Minio.Exceptions;
using SimApi.Configs;
using Minio.DataModel.Args;
using SimApi.Configurations;
namespace SimApi.Helpers;
namespace SimApi.Helpers
{
public class SimApiStorage
{
private MinioClient Mc { get; }
private IMinioClient Mc { get; }
public MinioClient Client => Mc;
public IMinioClient Client => Mc;
private string ServeUrl { get; }
private string Endpoint { get; }
public string Bucket { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
@@ -23,6 +26,7 @@ namespace SimApi.Helpers
{
var options = apiOptions.SimApiStorageOptions;
HttpContextAccessor = httpContextAccessor;
Endpoint = options.Endpoint;
var useSsl = false;
string endpoint;
if (options.Endpoint.StartsWith("http://"))
@@ -40,6 +44,7 @@ namespace SimApi.Helpers
}
ServeUrl = options.ServeUrl;
if (ServeUrl.EndsWith('/')) throw new Exception("SimApiStorage: ServeUrl must not end with /");
Bucket = options.Bucket;
var mcb = new MinioClient().WithEndpoint(endpoint)
.WithCredentials(options.AccessKey, options.SecretKey);
@@ -47,6 +52,7 @@ namespace SimApi.Helpers
{
mcb = mcb.WithSSL();
}
Mc = mcb.Build();
var found = Mc.BucketExistsAsync(new BucketExistsArgs().WithBucket(Bucket)).Result;
@@ -62,10 +68,13 @@ namespace SimApi.Helpers
/// <param name="path"></param>
/// <param name="expire"></param>
/// <returns></returns>
public string GetUploadUrl(string path, int expire = 7200)
public GetUploadUrlResponse GetUploadUrl(string path, int expire = 7200)
{
return Mc.PresignedPutObjectAsync(new PresignedPutObjectArgs().WithBucket(Bucket)
.WithObject(path).WithExpiry(expire)).Result;
CheckPath(path);
var obj = path.TrimStart('/');
var uploadUrl = Mc.PresignedPutObjectAsync(new PresignedPutObjectArgs().WithBucket(Bucket)
.WithObject(obj).WithExpiry(expire)).Result;
return new GetUploadUrlResponse(uploadUrl, $"{ServeUrl}{path}", path);
}
/// <summary>
@@ -76,20 +85,38 @@ namespace SimApi.Helpers
/// <returns></returns>
public string GetDownloadUrl(string path, int expire = 600)
{
CheckPath(path);
path = path.TrimStart('/');
return Mc.PresignedGetObjectAsync(new PresignedGetObjectArgs().WithBucket(Bucket).WithObject(path)
.WithExpiry(expire)).Result;
}
public string UploadFile(string path, Stream stream, string contentType = "image/png")
/// <summary>
/// 直接上传文件
/// </summary>
/// <param name="path"></param>
/// <param name="stream"></param>
/// <param name="contentType"></param>
public void UploadFile(string path, Stream stream, string contentType = "image/png")
{
CheckPath(path);
path = path.TrimStart('/');
Mc.PutObjectAsync(new PutObjectArgs().WithBucket(Bucket).WithObject(path).WithObjectSize(stream.Length)
.WithStreamData(stream).WithContentType(contentType)).Wait();
return null;
}
/// <summary>
/// 使用path获取完整的访问URL
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public string FullUrl(string path)
{
if (string.IsNullOrEmpty(path)) return path;
if(path.StartsWith("http://") || path.StartsWith("https://")) return path;
if (!(path.StartsWith('/') || path.StartsWith("~/"))) return path;
var httpRequest = HttpContextAccessor.HttpContext?.Request;
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
if (string.IsNullOrEmpty(path))
@@ -97,7 +124,44 @@ namespace SimApi.Helpers
return path;
}
return path.StartsWith("~") ? url + path.Substring(1, path.Length - 1) : $"{ServeUrl}{path}";
return path.StartsWith('~') ? string.Concat(url, path.AsSpan(1, path.Length - 1)) : $"{ServeUrl}{path}";
}
/// <summary>
/// 获取一个Path得访问URL
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string? GetUrl(string? path)
{
if (string.IsNullOrEmpty(path)) return path;
if (path.StartsWith("~/"))
{
var httpRequest = HttpContextAccessor.HttpContext?.Request;
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
return string.Concat(url, path.AsSpan(1, path.Length - 1));
}
if (path.StartsWith('/'))
{
return $"{ServeUrl}{path}";
}
return path;
}
/// <summary>
/// 从URL中获取相对路径 (如果url不是当前服务器的url,则原样返回)
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string? GetPath(string? url)
{
return url?.Replace($"{Endpoint}/{Bucket}", string.Empty).Replace(ServeUrl,string.Empty);
}
private void CheckPath(string path)
{
if (!path.StartsWith('/')) throw new Exception("path must start with /");
}
}
public record GetUploadUrlResponse(string UploadUrl, string DownloadUrl, string Path);
+24 -8
View File
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
@@ -7,8 +8,8 @@ using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Text.Unicode;
namespace SimApi.Helpers
{
namespace SimApi.Helpers;
public static class SimApiUtil
{
/// <summary>
@@ -50,16 +51,15 @@ namespace SimApi.Helpers
/// <returns></returns>
public static string Md5(string source, string mode = "x2")
{
var sor = Encoding.UTF8.GetBytes(source);
var md5 = MD5.Create();
var result = md5.ComputeHash(sor);
var strbul = new StringBuilder(40);
var sourceBytes = Encoding.UTF8.GetBytes(source);
var result = MD5.HashData(sourceBytes);
var stringBuilder = new StringBuilder(40);
foreach (var t in result)
{
strbul.Append(t.ToString(mode));
stringBuilder.Append(t.ToString(mode));
}
return strbul.ToString();
return stringBuilder.ToString();
}
/// <summary>
@@ -71,5 +71,21 @@ namespace SimApi.Helpers
{
return JsonSerializer.Serialize(obj, JsonOption);
}
/// <summary>
/// 分页
/// </summary>
/// <param name="query"></param>
/// <param name="page">页码</param>
/// <param name="count">每页数量</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IQueryable<T> Paginate<T>(this IQueryable<T> query, int page, int count)
{
if (page < 1)
page = 1;
if (count <= 0)
count = 10;
return query.Skip((page - 1) * count).Take(count);
}
}
+4 -11
View File
@@ -2,17 +2,10 @@ using System;
using Microsoft.Extensions.Logging;
using SimApi.Helpers;
namespace SimApi.Logger
{
public class SimApiLogger : ILogger
{
private string Name { get; }
namespace SimApi.Logger;
public SimApiLogger(string name)
public class SimApiLogger(string name) : ILogger
{
Name = name;
}
public IDisposable BeginScope<TState>(TState state) => default!;
public bool IsEnabled(LogLevel logLevel) => true;
@@ -30,12 +23,12 @@ namespace SimApi.Logger
_ => ConsoleColor.White
};
var message =
$"[ {Name} ][ {SimApiUtil.CstNow.ToString("yyyy-MM-dd HH:mm:ss:ffff")} ][ {logLevel.ToString()} ]\n{state}\n";
$"[ {name} ][ {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")} ][ {logLevel.ToString()} ]\n{state}\n";
if (exception != null)
{
message += $"{exception}\n";
}
Console.WriteLine(message);
}
}
}
+3 -5
View File
@@ -1,12 +1,11 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
namespace SimApi.Logger
{
namespace SimApi.Logger;
public class SimApiLoggerProvider : ILoggerProvider
{
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers =
new ConcurrentDictionary<string, SimApiLogger>();
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers = new();
public ILogger CreateLogger(string categoryName)
@@ -19,4 +18,3 @@ namespace SimApi.Logger
_loggers.Clear();
}
}
}
+10 -17
View File
@@ -3,39 +3,32 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi.Middlewares;
namespace SimApi.Middlewares
{
/// <summary>
/// 认证信息获取中间件
/// </summary>
public class SimApiAuthMiddleware
public class SimApiAuthMiddleware(RequestDelegate next)
{
private RequestDelegate Next { get; }
public SimApiAuthMiddleware(RequestDelegate next)
{
Next = next;
}
public Task Invoke(HttpContext httpContext, IDistributedCache cache)
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
{
string token = null;
if (httpContext.Request.Headers.ContainsKey("Token"))
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
{
token = httpContext.Request.Headers["Token"];
token = header;
}
if (!string.IsNullOrEmpty(token))
{
var login = cache.GetString(token);
var login = auth.GetLogin(token);
if (login != null)
{
httpContext.Items.Add("LoginInfo", JsonSerializer.Deserialize<SimApiLoginItem>(login));
httpContext.Items.Add("LoginInfo", login);
}
}
return Next(httpContext);
}
return next(httpContext);
}
}
+21 -32
View File
@@ -6,45 +6,37 @@ using SimApi.Communications;
using Microsoft.Extensions.Logging;
using SimApi.Exceptions;
namespace SimApi.Middlewares
{
namespace SimApi.Middlewares;
/// <summary>
/// 异常处理中间件
/// </summary>
public class SimApiExceptionMiddleware
public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExceptionMiddleware> log)
{
private RequestDelegate Next { get; }
private ILogger<SimApiExceptionMiddleware> Log { get; }
public SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExceptionMiddleware> log)
{
Log = log;
Next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers.ContainsKey("Query-Id"))
if (context.Request.Headers.TryGetValue("Query-Id", out var header))
{
context.Response.Headers["Query-Id"] = context.Request.Headers["Query-Id"];
context.Response.Headers["Query-Id"] = header;
}
var response = new SimApiBaseResponse();
SimApiBaseResponse response;
try
{
await Next(context);
if (context.Response.StatusCode != 200)
{
if (!new[]
{
301, 302
}.Contains(context.Response.StatusCode))
await next(context);
switch (context.Response.StatusCode)
{
case 200:
break;
case 404:
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
case 301:
case 302:
break;
default:
throw new SimApiException(context.Response.StatusCode);
}
}
}
catch (SimApiException ex)
{
response = string.IsNullOrEmpty(ex.Message)
@@ -55,8 +47,8 @@ namespace SimApi.Middlewares
}
catch (Exception ex)
{
Log.LogError(ex.Message);
Log.LogError(ex.StackTrace);
log.LogError("{Msg}", ex.Message);
log.LogError("{Msg}", ex.StackTrace);
response = new SimApiBaseResponse(500, ex.Message);
ErrorResponse(context, response);
}
@@ -67,14 +59,11 @@ namespace SimApi.Middlewares
/// </summary>
/// <param name="context"></param>
/// <param name="response"></param>
private void ErrorResponse(HttpContext context, SimApiBaseResponse response)
{
if (!context.Response.HasStarted)
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
{
if (context.Response.HasStarted) return;
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "application/json");
context.Response.Headers.Append("Content-Type", "application/json");
context.Response.WriteAsync(response.ToString());
}
}
}
}
+6 -11
View File
@@ -1,21 +1,17 @@
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text.Json;
using SimApi.Helpers;
namespace SimApi.Models
{
namespace SimApi.Models;
public class SimApiBaseModel
{
[Column(Order = 1)]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Column(Order = 1)] public string Id { get; set; } = Guid.NewGuid().ToString();
[Column(Order = 9998)]
public DateTime UpdatedAt { get; set; } = SimApiUtil.CstNow;
[Column(Order = 9998)] public DateTime UpdatedAt { get; set; } = DateTime.Now;
[Column(Order = 9999)]
public DateTime CreatedAt { get; set; } = SimApiUtil.CstNow;
[Column(Order = 9999)] public DateTime CreatedAt { get; set; } = DateTime.Now;
protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" };
@@ -85,7 +81,6 @@ namespace SimApi.Models
/// <returns></returns>
public void UpdateTime()
{
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, SimApiUtil.CstNow);
}
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, DateTime.Now);
}
}
+5 -5
View File
@@ -14,7 +14,7 @@
<SynchReleaseVersion>false</SynchReleaseVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageVersion>5.0.2</PackageVersion>
<TargetFrameworks>net7.0;net8.0</TargetFrameworks>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
@@ -25,10 +25,10 @@
<Folder Include="Exceptions\"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Minio" Version="4.0.7" />
<PackageReference Include="RabbitMQ.Client" Version="6.6.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0" />
<PackageReference Include="Minio" Version="6.0.3" />
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
+6 -5
View File
@@ -6,11 +6,11 @@ using Microsoft.OpenApi.Models;
using SimApi.Middlewares;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Logging;
using SimApi.Configs;
using SimApi.Configurations;
using SimApi.Logger;
namespace SimApi
{
namespace SimApi;
/// <summary>
/// 加入系统的扩展信息
/// </summary>
@@ -30,10 +30,11 @@ namespace SimApi
logger.AddProvider(new SimApiLoggerProvider());
});
}
// 是否使用 AUTH
if (simApiOptions.EnableSimApiAuth)
{
builder.AddScoped<SimApiAuth>();
builder.AddSingleton<SimApiAuth>();
}
if (simApiOptions.EnableCors)
@@ -199,6 +200,7 @@ namespace SimApi
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
if (options.EnableForwardHeaders)
{
logger.LogInformation("开始配置ForwardedHeaders...");
@@ -262,4 +264,3 @@ namespace SimApi
return builder;
}
}
}
-3
View File
@@ -1,11 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using RabbitMQ.Client.Events;
using SimApi.Communications;
using SimApi.Helpers;
+5 -5
View File
@@ -2,10 +2,6 @@ using System;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;
@@ -52,8 +48,12 @@ public partial class Synapse
var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption);
param = new[] { paramObj };
}
var ret = mt.Invoke(callClass, param);
res = new SimApiBaseResponse<object>(ret);
res = new SimApiBaseResponse<object>
{
Data = ret
};
}
catch (TargetInvocationException e)
{
+10 -1
View File
@@ -8,7 +8,7 @@ using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Configs;
using SimApi.Configurations;
using SimApi.Helpers;
namespace SimApi;
@@ -50,6 +50,7 @@ public partial class Synapse
{
Logger.LogCritical("Synapse初始化失败: AppName or SysName 错误");
}
Options.AppId ??= Guid.NewGuid().ToString();
Logger.LogInformation("System Name: {SysName}\nApp Name: {AppName}\nAppId: {AppId}", Options.SysName,
Options.AppName, Options.AppId);
@@ -76,10 +77,12 @@ public partial class Synapse
RunRpcClient();
Logger.LogInformation("Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
}
if (RpcRegistry.Count > 0)
{
RunRpcServer();
}
if (EventRegistry.Count > 0)
{
RunEventServer();
@@ -99,6 +102,7 @@ public partial class Synapse
var data = FireRpc(appName, method, param);
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
}
return res as SimApiBaseResponse<T>;
}
@@ -152,12 +156,14 @@ public partial class Synapse
channel.BasicQos(0, processNum, false);
log += $"最大处理器数量: {processNum}";
}
Logger.LogInformation(log);
}
catch (ConnectFailureException e)
{
Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e);
}
return channel;
}
@@ -173,6 +179,7 @@ public partial class Synapse
{
Logger.LogError("Failed to declare Exchange.\n {Err}", e);
}
channel.Close();
Logger.LogDebug("Exchange Channel Closed");
}
@@ -204,6 +211,7 @@ public partial class Synapse
});
}
}
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
{
var attribute =
@@ -220,6 +228,7 @@ public partial class Synapse
}
}
}
var events = EventRegistry.Aggregate(string.Empty,
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
var rpcList = RpcRegistry.Aggregate(string.Empty,