Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82f7e0fc00 | ||
|
|
f4bc6dc080 | ||
|
|
56b0490d1e | ||
|
|
45e19c3561 | ||
|
|
04b2be1bb7 | ||
|
|
f78c3a0e0d | ||
|
|
506704fd90 | ||
|
|
786051ddbf | ||
|
|
d9ff4ae422 | ||
|
|
986b4e74e6 | ||
|
|
2257ba5b2a | ||
|
|
c40f8d664d | ||
|
|
a1f10b9c09 | ||
|
|
6ef7aca8ae | ||
|
|
4171756c54 | ||
|
|
c68cfa6192 | ||
|
|
8344567ac6 | ||
|
|
99b26d99f6 | ||
|
|
cb291691d5 | ||
|
|
47a48d0103 |
@@ -14,7 +14,7 @@ jobs:
|
|||||||
- name: Setup .NET Core
|
- name: Setup .NET Core
|
||||||
uses: actions/setup-dotnet@v1
|
uses: actions/setup-dotnet@v1
|
||||||
with:
|
with:
|
||||||
dotnet-version: "7.0.100"
|
dotnet-version: "8.0.200"
|
||||||
- name: Publish
|
- name: Publish
|
||||||
run: |
|
run: |
|
||||||
version=`git describe --tags`
|
version=`git describe --tags`
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ using Microsoft.AspNetCore.Mvc.Filters;
|
|||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
namespace SimApi.Attributes
|
namespace SimApi.Attributes;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 检测登录中间件
|
/// 检测登录中间件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -19,10 +19,7 @@ namespace SimApi.Attributes
|
|||||||
//默认是user登录类型
|
//默认是user登录类型
|
||||||
public SimApiAuthAttribute()
|
public SimApiAuthAttribute()
|
||||||
{
|
{
|
||||||
Types = new[]
|
Types = new[] { "user" };
|
||||||
{
|
|
||||||
"user"
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//只检测一种用户类型的快捷方式
|
//只检测一种用户类型的快捷方式
|
||||||
@@ -40,10 +37,7 @@ namespace SimApi.Attributes
|
|||||||
//只检测一种用户类型的快捷方式
|
//只检测一种用户类型的快捷方式
|
||||||
public SimApiAuthAttribute(string type, string url)
|
public SimApiAuthAttribute(string type, string url)
|
||||||
{
|
{
|
||||||
Types = new[]
|
Types = new[] { type };
|
||||||
{
|
|
||||||
type
|
|
||||||
};
|
|
||||||
new HttpPostAttribute(url);
|
new HttpPostAttribute(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,4 +56,3 @@ namespace SimApi.Attributes
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
using System;
|
using System;
|
||||||
using Swashbuckle.AspNetCore.Annotations;
|
using Swashbuckle.AspNetCore.Annotations;
|
||||||
|
|
||||||
namespace SimApi.Attributes
|
namespace SimApi.Attributes;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 快捷自定义接口文档类
|
/// 快捷自定义接口文档类
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -22,4 +22,3 @@ namespace SimApi.Attributes
|
|||||||
// Produces = new[] {"application/json"};
|
// Produces = new[] {"application/json"};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -1,23 +1,37 @@
|
|||||||
namespace SimApi.Communications
|
using System.ComponentModel.DataAnnotations;
|
||||||
{
|
|
||||||
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 只有ID的请求
|
/// 只有ID的请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiIdOnlyRequest(int Id);
|
public class SimApiIdOnlyRequest
|
||||||
|
{
|
||||||
|
[Required] public int Id { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 只有ID的请求(字符串)
|
/// 只有ID的请求(字符串)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiStringIdOnlyRequest(string Id);
|
public class SimApiStringIdOnlyRequest
|
||||||
|
{
|
||||||
|
[Required] public string Id { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 动态类型单字段请求
|
/// 动态类型单字段请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public record SimApiOneFieldRequest<T>(T Data);
|
public class SimApiOneFieldRequest<T>
|
||||||
|
{
|
||||||
|
[Required] public T Data { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 基础分页请求
|
/// 基础分页请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiBasePageRequest(int Page, int Count);
|
public class SimApiBasePageRequest
|
||||||
|
{
|
||||||
|
[Required] public int Page { get; set; }
|
||||||
|
[Required] public int Count { get; set; }
|
||||||
}
|
}
|
||||||
@@ -2,42 +2,31 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace SimApi.Communications
|
namespace SimApi.Communications;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 基础相应
|
/// 基础相应
|
||||||
/// </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>
|
||||||
/// 默认错误代码对应提示信息
|
/// 默认错误代码对应提示信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static readonly Dictionary<int, string> MsgBox = new()
|
private static readonly Dictionary<int, string> MsgBox = new()
|
||||||
{
|
{
|
||||||
{
|
{ 200, "成功" },
|
||||||
200, "成功"
|
{ 204, "没有数据" },
|
||||||
},
|
{ 400, "参数错误" },
|
||||||
{
|
{ 401, "需要登录" },
|
||||||
204, "没有数据"
|
{ 403, "无权访问" },
|
||||||
},
|
{ 404, "接口不存在" },
|
||||||
{
|
{ 500, "服务器错误" }
|
||||||
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>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public record SimApiBasePageResponse<T>
|
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
||||||
(T List, int Page = 1, int Count = 1, int Total = 1, int Code = 200,
|
{
|
||||||
string Message = "成功") : SimApiBaseResponse(Code, Message);
|
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>
|
/// <summary>
|
||||||
/// 动态Data返回
|
/// 动态Data返回
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public record SimApiBaseResponse<T>(T Data, int Code = 200, string Message = "成功") : SimApiBaseResponse(Code,
|
public class SimApiBaseResponse<T>() : SimApiBaseResponse
|
||||||
Message);
|
{
|
||||||
|
public T Data { get; set; }
|
||||||
|
|
||||||
|
public SimApiBaseResponse(T data) : this()
|
||||||
|
{
|
||||||
|
Data = data;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
namespace SimApi.Communications
|
using System.Collections.Generic;
|
||||||
{
|
|
||||||
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 登录信息中间件
|
/// 登录信息中间件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiLoginItem(string Id, string[] Type);
|
public record SimApiLoginItem(string Id, string[] Type,Dictionary<string,string> Meta = null);
|
||||||
}
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
using System;
|
using System.Collections.Generic;
|
||||||
using System.Collections.Generic;
|
|
||||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||||
|
|
||||||
namespace SimApi.Configs
|
namespace SimApi.Configurations;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档组配置
|
/// 文档组配置
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -31,9 +30,13 @@ namespace SimApi.Configs
|
|||||||
public class SimApiAuthOption
|
public class SimApiAuthOption
|
||||||
{
|
{
|
||||||
public string[] Type { get; set; } = new[] { "SimApiAuth" };
|
public string[] Type { get; set; } = new[] { "SimApiAuth" };
|
||||||
|
|
||||||
public string Description { get; set; } = "认证服务器颁发的AccessToken";
|
public string Description { get; set; } = "认证服务器颁发的AccessToken";
|
||||||
|
|
||||||
public string AuthorizationUrl { get; set; }
|
public string AuthorizationUrl { get; set; }
|
||||||
|
|
||||||
public string TokenUrl { get; set; }
|
public string TokenUrl { get; set; }
|
||||||
|
|
||||||
public Dictionary<string, string> Scopes { get; set; }
|
public Dictionary<string, string> Scopes { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,4 +73,3 @@ namespace SimApi.Configs
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public SubmitMethod[] SupportedMethod { get; set; } = new[] { SubmitMethod.Post };
|
public SubmitMethod[] SupportedMethod { get; set; } = new[] { SubmitMethod.Post };
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace SimApi.Configs
|
namespace SimApi.Configurations;
|
||||||
{
|
|
||||||
public class SimApiOptions
|
public class SimApiOptions
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -11,7 +11,7 @@ namespace SimApi.Configs
|
|||||||
public bool EnableCors { get; set; } = true;
|
public bool EnableCors { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用SimapiAuth,一个简单的基于Header Token的认证方式。
|
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiAuth { get; set; } = false;
|
public bool EnableSimApiAuth { get; set; } = false;
|
||||||
@@ -90,4 +90,3 @@ namespace SimApi.Configs
|
|||||||
options?.Invoke(SimApiStorageOptions);
|
options?.Invoke(SimApiStorageOptions);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
namespace SimApi.Configs
|
namespace SimApi.Configurations;
|
||||||
{
|
|
||||||
public class SimApiStorageOptions
|
public class SimApiStorageOptions
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -21,4 +21,3 @@ namespace SimApi.Configs
|
|||||||
|
|
||||||
public string SecretKey { get; set; }
|
public string SecretKey { get; set; }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -1,29 +1,23 @@
|
|||||||
namespace SimApi.Configs;
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
public class SimApiSynapseOptions
|
public class SimApiSynapseOptions
|
||||||
{
|
{
|
||||||
public string MqHost { get; set; }
|
/// <summary>
|
||||||
|
/// Mqtt服务器的Websocket地址
|
||||||
|
/// </summary>
|
||||||
|
public string Websocket { get; set; }
|
||||||
|
|
||||||
public int MqPort { get; set; }
|
public string Username { get; set; }
|
||||||
|
|
||||||
public string MqUser { get; set; }
|
public string Password { get; set; }
|
||||||
|
|
||||||
public string MqPass { get; set; }
|
|
||||||
|
|
||||||
public string MqVHost { get; set; } = "/";
|
|
||||||
|
|
||||||
public string SysName { get; set; }
|
public string SysName { get; set; }
|
||||||
|
|
||||||
public string AppName { get; set; }
|
public string AppName { get; set; }
|
||||||
|
|
||||||
public string AppId { get; set; }
|
public string AppId { get; set; }
|
||||||
|
|
||||||
public int RpcTimeout { get; set; } = 3;
|
public int RpcTimeout { get; set; } = 3;
|
||||||
|
|
||||||
public ushort EventProcessorNum { get; set; } = 20;
|
|
||||||
|
|
||||||
public ushort RpcProcessorNum { get; set; } = 20;
|
|
||||||
|
|
||||||
public bool DisableEventClient { get; set; } = false;
|
public bool DisableEventClient { get; set; } = false;
|
||||||
|
|
||||||
public bool DisableRpcClient { get; set; } = false;
|
public bool DisableRpcClient { get; set; } = false;
|
||||||
|
|||||||
@@ -4,10 +4,9 @@ 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 SimApi.Exceptions;
|
||||||
using SimApi.Attributes;
|
|
||||||
|
|
||||||
namespace SimApi.Controllers
|
namespace SimApi.Controllers;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 基础控制器,所有控制器均继承本控制器
|
/// 基础控制器,所有控制器均继承本控制器
|
||||||
/// 1. 自动验证请求参数
|
/// 1. 自动验证请求参数
|
||||||
@@ -51,12 +50,12 @@ namespace SimApi.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 检测条件,根据条件返回报错
|
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="condition">检测条件</param>
|
/// <param name="condition">检测条件</param>
|
||||||
/// <param name="code">错误代码</param>
|
/// <param name="code">错误代码</param>
|
||||||
/// <param name="message">错误描述</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)
|
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>
|
/// <summary>
|
||||||
/// 检测给定的变量是否为NUll
|
/// 检测给定的变量是否为NUll
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="condition">检测条件</param>
|
/// <param name="condition">检测条件</param>
|
||||||
/// <param name="code">错误代码</param>
|
/// <param name="code">错误代码</param>
|
||||||
/// <param name="message">错误描述</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);
|
ErrorWhen(condition == null, code, message);
|
||||||
}
|
}
|
||||||
@@ -81,7 +104,6 @@ namespace SimApi.Controllers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
protected SimApiBaseResponse<string> UploadFile()
|
protected SimApiBaseResponse<string> UploadFile()
|
||||||
{
|
{
|
||||||
return new SimApiBaseResponse<string>(null);
|
return new SimApiBaseResponse<string>();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,13 @@
|
|||||||
using System;
|
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;
|
||||||
{
|
|
||||||
[ApiExplorerSettings(GroupName = "api")]
|
[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>
|
||||||
/// 错误回馈页面
|
/// 错误回馈页面
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -36,7 +28,10 @@ namespace SimApi.Controllers
|
|||||||
public SimApiBaseResponse<string> CheckLogin()
|
public SimApiBaseResponse<string> CheckLogin()
|
||||||
{
|
{
|
||||||
ErrorWhenNull(LoginInfo, 401);
|
ErrorWhenNull(LoginInfo, 401);
|
||||||
return new SimApiBaseResponse<string>(LoginInfo.Id);
|
return new SimApiBaseResponse<string>
|
||||||
|
{
|
||||||
|
Data = LoginInfo.Id
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -48,13 +43,18 @@ namespace SimApi.Controllers
|
|||||||
{
|
{
|
||||||
string token = null;
|
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();
|
return new SimApiBaseResponse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost("/logined"),SimApiAuth]
|
||||||
|
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
||||||
|
{
|
||||||
|
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
namespace SimApi.Exceptions
|
|
||||||
{
|
namespace SimApi.Exceptions;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Api错误捕获异常
|
/// Api错误捕获异常
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiException : Exception
|
public class SimApiException(int code, string message = "") : Exception(message)
|
||||||
{
|
{
|
||||||
public int Code { get; }
|
public int Code { get; } = code;
|
||||||
|
|
||||||
public SimApiException(int code, string message = "") : base(message)
|
|
||||||
{
|
|
||||||
Code = code;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+43
-21
@@ -1,34 +1,28 @@
|
|||||||
|
#nullable enable
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
namespace SimApi.Helpers;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 认证助手
|
/// 认证助手
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiAuth
|
public class SimApiAuth(IDistributedCache cache)
|
||||||
{
|
{
|
||||||
private IDistributedCache Cache { get; }
|
|
||||||
|
|
||||||
public SimApiAuth(IDistributedCache cache)
|
|
||||||
{
|
|
||||||
Cache = cache;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 产生一个Token记录并返回Token
|
/// 产生一个Token记录并返回Token
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id"></param>
|
/// <param name="id"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="meta"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <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[]
|
return Login(id, meta, new[] { type }, token);
|
||||||
{
|
|
||||||
type
|
|
||||||
}, token);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -36,15 +30,44 @@ namespace SimApi.Helpers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id"></param>
|
/// <param name="id"></param>
|
||||||
/// <param name="type"></param>
|
/// <param name="type"></param>
|
||||||
|
/// <param name="meta"></param>
|
||||||
|
/// <param name="uuid"></param>
|
||||||
/// <returns></returns>
|
/// <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();
|
uuid ??= Guid.NewGuid().ToString();
|
||||||
var loginItem = new SimApiLoginItem(id, type);
|
var loginItem = new SimApiLoginItem(id, type, meta);
|
||||||
Cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
|
cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
|
||||||
return uuid;
|
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>
|
||||||
/// 退出登陆
|
/// 退出登陆
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -53,8 +76,7 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(uuid))
|
if (!string.IsNullOrEmpty(uuid))
|
||||||
{
|
{
|
||||||
Cache.Remove(uuid);
|
cache.Remove(uuid);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+77
-13
@@ -1,20 +1,23 @@
|
|||||||
using System;
|
#nullable enable
|
||||||
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Minio;
|
using Minio;
|
||||||
using Minio.Exceptions;
|
using Minio.DataModel.Args;
|
||||||
using SimApi.Configs;
|
using SimApi.Configurations;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
|
||||||
{
|
|
||||||
public class SimApiStorage
|
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 ServeUrl { get; }
|
||||||
|
|
||||||
|
private string Endpoint { get; }
|
||||||
|
|
||||||
public string Bucket { get; }
|
public string Bucket { get; }
|
||||||
|
|
||||||
private IHttpContextAccessor HttpContextAccessor { get; }
|
private IHttpContextAccessor HttpContextAccessor { get; }
|
||||||
@@ -23,6 +26,7 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
var options = apiOptions.SimApiStorageOptions;
|
var options = apiOptions.SimApiStorageOptions;
|
||||||
HttpContextAccessor = httpContextAccessor;
|
HttpContextAccessor = httpContextAccessor;
|
||||||
|
Endpoint = options.Endpoint;
|
||||||
var useSsl = false;
|
var useSsl = false;
|
||||||
string endpoint;
|
string endpoint;
|
||||||
if (options.Endpoint.StartsWith("http://"))
|
if (options.Endpoint.StartsWith("http://"))
|
||||||
@@ -40,6 +44,7 @@ namespace SimApi.Helpers
|
|||||||
}
|
}
|
||||||
|
|
||||||
ServeUrl = options.ServeUrl;
|
ServeUrl = options.ServeUrl;
|
||||||
|
if (ServeUrl.EndsWith('/')) throw new Exception("SimApiStorage: ServeUrl must not end with /");
|
||||||
Bucket = options.Bucket;
|
Bucket = options.Bucket;
|
||||||
var mcb = new MinioClient().WithEndpoint(endpoint)
|
var mcb = new MinioClient().WithEndpoint(endpoint)
|
||||||
.WithCredentials(options.AccessKey, options.SecretKey);
|
.WithCredentials(options.AccessKey, options.SecretKey);
|
||||||
@@ -47,6 +52,7 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
mcb = mcb.WithSSL();
|
mcb = mcb.WithSSL();
|
||||||
}
|
}
|
||||||
|
|
||||||
Mc = mcb.Build();
|
Mc = mcb.Build();
|
||||||
|
|
||||||
var found = Mc.BucketExistsAsync(new BucketExistsArgs().WithBucket(Bucket)).Result;
|
var found = Mc.BucketExistsAsync(new BucketExistsArgs().WithBucket(Bucket)).Result;
|
||||||
@@ -62,10 +68,13 @@ namespace SimApi.Helpers
|
|||||||
/// <param name="path"></param>
|
/// <param name="path"></param>
|
||||||
/// <param name="expire"></param>
|
/// <param name="expire"></param>
|
||||||
/// <returns></returns>
|
/// <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)
|
CheckPath(path);
|
||||||
.WithObject(path).WithExpiry(expire)).Result;
|
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>
|
/// <summary>
|
||||||
@@ -76,20 +85,38 @@ namespace SimApi.Helpers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string GetDownloadUrl(string path, int expire = 600)
|
public string GetDownloadUrl(string path, int expire = 600)
|
||||||
{
|
{
|
||||||
|
CheckPath(path);
|
||||||
|
path = path.TrimStart('/');
|
||||||
return Mc.PresignedGetObjectAsync(new PresignedGetObjectArgs().WithBucket(Bucket).WithObject(path)
|
return Mc.PresignedGetObjectAsync(new PresignedGetObjectArgs().WithBucket(Bucket).WithObject(path)
|
||||||
.WithExpiry(expire)).Result;
|
.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)
|
Mc.PutObjectAsync(new PutObjectArgs().WithBucket(Bucket).WithObject(path).WithObjectSize(stream.Length)
|
||||||
.WithStreamData(stream).WithContentType(contentType)).Wait();
|
.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)
|
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 httpRequest = HttpContextAccessor.HttpContext?.Request;
|
||||||
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
|
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
|
||||||
if (string.IsNullOrEmpty(path))
|
if (string.IsNullOrEmpty(path))
|
||||||
@@ -97,7 +124,44 @@ namespace SimApi.Helpers
|
|||||||
return path;
|
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
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Linq;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
@@ -7,8 +8,8 @@ using System.Text.Json.Serialization;
|
|||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Text.Unicode;
|
using System.Text.Unicode;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
namespace SimApi.Helpers;
|
||||||
{
|
|
||||||
public static class SimApiUtil
|
public static class SimApiUtil
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -50,16 +51,15 @@ namespace SimApi.Helpers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Md5(string source, string mode = "x2")
|
public static string Md5(string source, string mode = "x2")
|
||||||
{
|
{
|
||||||
var sor = Encoding.UTF8.GetBytes(source);
|
var sourceBytes = Encoding.UTF8.GetBytes(source);
|
||||||
var md5 = MD5.Create();
|
var result = MD5.HashData(sourceBytes);
|
||||||
var result = md5.ComputeHash(sor);
|
var stringBuilder = new StringBuilder(40);
|
||||||
var strbul = new StringBuilder(40);
|
|
||||||
foreach (var t in result)
|
foreach (var t in result)
|
||||||
{
|
{
|
||||||
strbul.Append(t.ToString(mode));
|
stringBuilder.Append(t.ToString(mode));
|
||||||
}
|
}
|
||||||
|
|
||||||
return strbul.ToString();
|
return stringBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -71,5 +71,21 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(obj, JsonOption);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+5
-11
@@ -2,17 +2,10 @@ using System;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Logger
|
namespace SimApi.Logger;
|
||||||
{
|
|
||||||
public class SimApiLogger : ILogger
|
|
||||||
{
|
|
||||||
private string Name { get; }
|
|
||||||
|
|
||||||
public SimApiLogger(string name)
|
public class SimApiLogger(string name) : ILogger
|
||||||
{
|
{
|
||||||
Name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IDisposable BeginScope<TState>(TState state) => default!;
|
public IDisposable BeginScope<TState>(TState state) => default!;
|
||||||
|
|
||||||
public bool IsEnabled(LogLevel logLevel) => true;
|
public bool IsEnabled(LogLevel logLevel) => true;
|
||||||
@@ -30,12 +23,13 @@ namespace SimApi.Logger
|
|||||||
_ => ConsoleColor.White
|
_ => ConsoleColor.White
|
||||||
};
|
};
|
||||||
var message =
|
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)
|
if (exception != null)
|
||||||
{
|
{
|
||||||
message += $"{exception}\n";
|
message += $"{exception}\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.WriteLine(message);
|
Console.WriteLine(message);
|
||||||
}
|
Console.ResetColor();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace SimApi.Logger
|
namespace SimApi.Logger;
|
||||||
{
|
|
||||||
public class SimApiLoggerProvider : ILoggerProvider
|
public class SimApiLoggerProvider : ILoggerProvider
|
||||||
{
|
{
|
||||||
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers =
|
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers = new();
|
||||||
new ConcurrentDictionary<string, SimApiLogger>();
|
|
||||||
|
|
||||||
|
|
||||||
public ILogger CreateLogger(string categoryName)
|
public ILogger CreateLogger(string categoryName)
|
||||||
@@ -19,4 +18,3 @@ namespace SimApi.Logger
|
|||||||
_loggers.Clear();
|
_loggers.Clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -3,39 +3,32 @@ using System.Threading.Tasks;
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.Middlewares;
|
||||||
|
|
||||||
namespace SimApi.Middlewares
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 认证信息获取中间件
|
/// 认证信息获取中间件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiAuthMiddleware
|
public class SimApiAuthMiddleware(RequestDelegate next)
|
||||||
{
|
{
|
||||||
private RequestDelegate Next { get; }
|
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
|
||||||
|
|
||||||
public SimApiAuthMiddleware(RequestDelegate next)
|
|
||||||
{
|
|
||||||
Next = next;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task Invoke(HttpContext httpContext, IDistributedCache cache)
|
|
||||||
{
|
{
|
||||||
string token = null;
|
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))
|
if (!string.IsNullOrEmpty(token))
|
||||||
{
|
{
|
||||||
var login = cache.GetString(token);
|
var login = auth.GetLogin(token);
|
||||||
if (login != null)
|
if (login != null)
|
||||||
{
|
{
|
||||||
httpContext.Items.Add("LoginInfo", JsonSerializer.Deserialize<SimApiLoginItem>(login));
|
httpContext.Items.Add("LoginInfo", login);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Next(httpContext);
|
return next(httpContext);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,45 +6,37 @@ using SimApi.Communications;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
namespace SimApi.Middlewares
|
namespace SimApi.Middlewares;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 异常处理中间件
|
/// 异常处理中间件
|
||||||
/// </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)
|
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
|
try
|
||||||
{
|
{
|
||||||
await Next(context);
|
await next(context);
|
||||||
if (context.Response.StatusCode != 200)
|
switch (context.Response.StatusCode)
|
||||||
{
|
|
||||||
if (!new[]
|
|
||||||
{
|
|
||||||
301, 302
|
|
||||||
}.Contains(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);
|
throw new SimApiException(context.Response.StatusCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (SimApiException ex)
|
catch (SimApiException ex)
|
||||||
{
|
{
|
||||||
response = string.IsNullOrEmpty(ex.Message)
|
response = string.IsNullOrEmpty(ex.Message)
|
||||||
@@ -55,8 +47,8 @@ namespace SimApi.Middlewares
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Log.LogError(ex.Message);
|
log.LogError("{Msg}", ex.Message);
|
||||||
Log.LogError(ex.StackTrace);
|
log.LogError("{Msg}", ex.StackTrace);
|
||||||
response = new SimApiBaseResponse(500, ex.Message);
|
response = new SimApiBaseResponse(500, ex.Message);
|
||||||
ErrorResponse(context, response);
|
ErrorResponse(context, response);
|
||||||
}
|
}
|
||||||
@@ -67,14 +59,11 @@ namespace SimApi.Middlewares
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
/// <param name="response"></param>
|
/// <param name="response"></param>
|
||||||
private void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
||||||
{
|
|
||||||
if (!context.Response.HasStarted)
|
|
||||||
{
|
{
|
||||||
|
if (context.Response.HasStarted) return;
|
||||||
context.Response.StatusCode = 200;
|
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());
|
context.Response.WriteAsync(response.ToString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,17 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.ComponentModel.DataAnnotations.Schema;
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Models
|
namespace SimApi.Models;
|
||||||
{
|
|
||||||
public class SimApiBaseModel
|
public class SimApiBaseModel
|
||||||
{
|
{
|
||||||
[Column(Order = 1)]
|
[Column(Order = 1)] public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
|
||||||
|
|
||||||
[Column(Order = 9998)]
|
[Column(Order = 9998)] public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
public DateTime UpdatedAt { get; set; } = SimApiUtil.CstNow;
|
|
||||||
|
|
||||||
[Column(Order = 9999)]
|
[Column(Order = 9999)] public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
public DateTime CreatedAt { get; set; } = SimApiUtil.CstNow;
|
|
||||||
|
|
||||||
protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" };
|
protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" };
|
||||||
|
|
||||||
@@ -85,7 +81,6 @@ namespace SimApi.Models
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public void UpdateTime()
|
public void UpdateTime()
|
||||||
{
|
{
|
||||||
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, SimApiUtil.CstNow);
|
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, DateTime.Now);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+5
-5
@@ -14,7 +14,7 @@
|
|||||||
<SynchReleaseVersion>false</SynchReleaseVersion>
|
<SynchReleaseVersion>false</SynchReleaseVersion>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
<PackageVersion>5.0.2</PackageVersion>
|
<PackageVersion>5.0.2</PackageVersion>
|
||||||
<TargetFrameworks>net7.0;net8.0</TargetFrameworks>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -25,10 +25,10 @@
|
|||||||
<Folder Include="Exceptions\"/>
|
<Folder Include="Exceptions\"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Minio" Version="4.0.7" />
|
<PackageReference Include="Minio" Version="6.0.3" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="6.6.0" />
|
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0" />
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ProjectExtensions>
|
<ProjectExtensions>
|
||||||
<MonoDevelop>
|
<MonoDevelop>
|
||||||
|
|||||||
+36
-5
@@ -5,12 +5,13 @@ using Microsoft.Extensions.DependencyInjection;
|
|||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
using SimApi.Middlewares;
|
using SimApi.Middlewares;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Configs;
|
using SimApi.Configurations;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
|
|
||||||
namespace SimApi
|
namespace SimApi;
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 加入系统的扩展信息
|
/// 加入系统的扩展信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -30,10 +31,11 @@ namespace SimApi
|
|||||||
logger.AddProvider(new SimApiLoggerProvider());
|
logger.AddProvider(new SimApiLoggerProvider());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 是否使用 AUTH
|
// 是否使用 AUTH
|
||||||
if (simApiOptions.EnableSimApiAuth)
|
if (simApiOptions.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
builder.AddScoped<SimApiAuth>();
|
builder.AddSingleton<SimApiAuth>();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableCors)
|
if (simApiOptions.EnableCors)
|
||||||
@@ -188,6 +190,35 @@ namespace SimApi
|
|||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static IHost UseSimApi(this IHost builder)
|
||||||
|
{
|
||||||
|
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||||
|
|
||||||
|
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
|
||||||
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
|
|
||||||
|
//请求一下检测存储错误
|
||||||
|
if (options.EnableSimApiStorage)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置SimApiStorage...");
|
||||||
|
builder.Services.GetService<SimApiStorage>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.EnableLowerUrl)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置使用URL小写...");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.EnableSynapse)
|
||||||
|
{
|
||||||
|
var synapse = builder.Services.GetRequiredService<Synapse>();
|
||||||
|
synapse.Init();
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 使用所有SimApi自定义中间件
|
/// 使用所有SimApi自定义中间件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -199,6 +230,7 @@ namespace SimApi
|
|||||||
|
|
||||||
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
|
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
|
||||||
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
if (options.EnableForwardHeaders)
|
if (options.EnableForwardHeaders)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置ForwardedHeaders...");
|
logger.LogInformation("开始配置ForwardedHeaders...");
|
||||||
@@ -262,4 +294,3 @@ namespace SimApi
|
|||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
+13
-19
@@ -1,31 +1,25 @@
|
|||||||
using System;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Encodings.Web;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Unicode;
|
using System.Threading;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using MQTTnet;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
private void RunEventClient()
|
private bool FireEvent(string eventName, object param, bool retain = false)
|
||||||
{
|
|
||||||
EventClientChannel = CreateChannel(0, "EventClient");
|
|
||||||
}
|
|
||||||
|
|
||||||
private void FireEvent(string eventName, object param)
|
|
||||||
{
|
{
|
||||||
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
||||||
var router = $"event.{Options.AppName}.{eventName}";
|
var topic = $"{Options.SysName}/{Options.AppName}/event/{eventName}";
|
||||||
var props = EventClientChannel.CreateBasicProperties();
|
var message = new MqttApplicationMessageBuilder()
|
||||||
props.AppId = Options.AppId;
|
.WithTopic(topic)
|
||||||
props.MessageId = Guid.NewGuid().ToString();
|
.WithPayload(paramJson)
|
||||||
props.ReplyTo = Options.AppName;
|
.WithRetainFlag(retain)
|
||||||
props.Type = eventName;
|
.Build();
|
||||||
EventClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson));
|
if (!Client!.IsConnected) return false;
|
||||||
Logger.LogDebug("Event Publish: {OptionsAppName}.{EventName}\n{ParamJson}", Options.AppName, eventName,
|
Client!.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
paramJson);
|
logger.LogDebug("Event Publish: {Event}@{App} {Json}", eventName, Options.AppName, paramJson);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+22
-23
@@ -1,10 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using RabbitMQ.Client.Events;
|
using MQTTnet;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
@@ -13,38 +14,36 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
private void RunEventServer()
|
private void RunEventServer()
|
||||||
{
|
{
|
||||||
EventServerChannel = CreateChannel(Options.EventProcessorNum, "EventServer");
|
var esTopicPrefix = $"{Options.SysName}/{Options.AppName}/event/";
|
||||||
var queue = $"{Options.SysName}_{Options.AppName}_event";
|
var eventSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
EventServerChannel.QueueDeclare(queue, true, false, true, null);
|
.WithTopicFilter(o =>
|
||||||
foreach (var ev in EventRegistry.Where(ev => !ev.Key.Contains('*') && !ev.Key.Contains('#')))
|
o.WithTopic($"$queue/{esTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
||||||
|
.Build();
|
||||||
|
Client.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
EventServerChannel.QueueBind(queue, Options.SysName, $"event.{ev.Key}", null);
|
if (!e.ApplicationMessage.Topic.StartsWith(esTopicPrefix)) return Task.CompletedTask;
|
||||||
}
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var consumer = new EventingBasicConsumer(EventServerChannel);
|
var eventName = e.ApplicationMessage.Topic.Replace(esTopicPrefix, string.Empty);
|
||||||
consumer.Received += (ch, ea) =>
|
logger.LogDebug("Synapse Event Receive: {AppName}.{EventName}\n{Body}",
|
||||||
{
|
Options.AppName, eventName, reqBody);
|
||||||
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
|
|
||||||
Logger.LogDebug("Event Receive: {BasicPropertiesReplyTo}.{BasicPropertiesType}\n{S}",
|
|
||||||
ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, reqBody);
|
|
||||||
|
|
||||||
var key = ea.RoutingKey.Replace("event.", string.Empty);
|
var method = EventRegistry.FirstOrDefault(x => x.Key == eventName);
|
||||||
var method = EventRegistry.FirstOrDefault(x => x.Key == key);
|
if (method == null) return Task.CompletedTask;
|
||||||
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
|
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method!.Class);
|
||||||
var mt = callClass.GetType().GetMethod(method.Method);
|
var mt = callClass.GetType().GetMethod(method.Method);
|
||||||
var pt = mt.GetParameters()[0].ParameterType;
|
var pt = mt!.GetParameters()[0].ParameterType;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
mt.Invoke(callClass, pt == typeof(string)
|
mt.Invoke(callClass, pt == typeof(string)
|
||||||
? new object[] { reqBody }
|
? new object[] { reqBody }
|
||||||
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
||||||
EventServerChannel.BasicAck(ea.DeliveryTag, false);
|
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Logger.LogError("Event Processor Error: {Err}", e.InnerException);
|
logger.LogError("SynapseEvent Processor Error: {Err}", ex.InnerException);
|
||||||
EventServerChannel.BasicNack(ea.DeliveryTag, false, false);
|
|
||||||
}
|
}
|
||||||
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
EventServerChannel.BasicConsume(queue, false, "", false, false, null, consumer);
|
Client.SubscribeAsync(eventSubOpts).Wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+47
-39
@@ -1,12 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
|
||||||
using System.Text.Encodings.Web;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Unicode;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Newtonsoft.Json.Serialization;
|
using MQTTnet;
|
||||||
using RabbitMQ.Client.Events;
|
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
@@ -14,57 +12,67 @@ namespace SimApi;
|
|||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
private Dictionary<string, byte[]> ResponseCache { get; } = new();
|
private Dictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
|
||||||
|
|
||||||
private void RunRpcClient()
|
private void RunRpcClient()
|
||||||
{
|
{
|
||||||
RpcClientChannel = CreateChannel(0, "RpcClient");
|
var rcTopic = $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
|
||||||
var queue = $"{Options.SysName}_{Options.AppName}_client_{Options.AppId}";
|
var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
var router = $"client.{Options.AppName}.{Options.AppId}";
|
.WithTopicFilter(o => o.WithTopic($"{rcTopic}+")).Build();
|
||||||
RpcClientChannel.QueueDeclare(queue, true, false, true, null);
|
Client.ApplicationMessageReceivedAsync += e =>
|
||||||
RpcClientChannel.QueueBind(queue, Options.SysName, router, null);
|
|
||||||
var consumer = new EventingBasicConsumer(RpcClientChannel);
|
|
||||||
consumer.Received += (ch, ea) =>
|
|
||||||
{
|
{
|
||||||
ResponseCache.Add(ea.BasicProperties.CorrelationId, ea.Body.ToArray());
|
if (!e.ApplicationMessage.Topic.StartsWith(rcTopic)) return Task.CompletedTask;
|
||||||
RpcClientChannel.BasicAck(ea.DeliveryTag, false);
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
Logger.LogDebug(
|
var messageId = e.ApplicationMessage.Topic.Replace(rcTopic, string.Empty);
|
||||||
"RPC Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
|
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
|
||||||
ea.BasicProperties.CorrelationId, ea.BasicProperties.Type, ea.BasicProperties.ReplyTo, Options.AppName,
|
tcs.SetResult(reqBody);
|
||||||
Encoding.UTF8.GetString(ea.Body.ToArray()));
|
ResponseCompletionSources.Remove(messageId);
|
||||||
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
RpcClientChannel.BasicConsume(queue, false, "", false, false, null, consumer);
|
Client.SubscribeAsync(rcSubOpts).Wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
private string FireRpc(string app, string action, object param)
|
private string FireRpc(string app, string action, object param)
|
||||||
{
|
{
|
||||||
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
||||||
var router = $"server.{app}";
|
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
|
||||||
string response;
|
var messageId = Guid.NewGuid().ToString();
|
||||||
var props = RpcClientChannel.CreateBasicProperties();
|
var tcs = new TaskCompletionSource<string>();
|
||||||
props.AppId = Options.AppId;
|
ResponseCompletionSources.Add(messageId, tcs);
|
||||||
props.MessageId = Guid.NewGuid().ToString();
|
var message = new MqttApplicationMessageBuilder()
|
||||||
props.Type = action;
|
.WithTopic(topic)
|
||||||
props.ReplyTo = Options.AppName;
|
.WithPayload(paramJson)
|
||||||
RpcClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson));
|
.WithResponseTopic($"{Options.AppName},{Options.AppId}")
|
||||||
Logger.LogDebug("RPC Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}",
|
.WithContentType(messageId)
|
||||||
props.MessageId,
|
.WithRetainFlag(false)
|
||||||
|
.Build();
|
||||||
|
if (!Client!.IsConnected) return null;
|
||||||
|
Client!.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
|
logger.LogDebug(
|
||||||
|
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}", messageId,
|
||||||
Options.AppName, action, app, paramJson);
|
Options.AppName, action, app, paramJson);
|
||||||
var ts = SimApiUtil.TimestampNow;
|
|
||||||
while (true)
|
string response;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (SimApiUtil.TimestampNow - ts > Options.RpcTimeout)
|
if (tcs.Task.Wait(Options.RpcTimeout * 1000))
|
||||||
|
{
|
||||||
|
response = tcs.Task.Result;
|
||||||
|
logger.LogDebug(
|
||||||
|
"Synapse RPC Client Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
|
||||||
|
messageId, action, app, Options.AppName, response);
|
||||||
|
}
|
||||||
|
else
|
||||||
{
|
{
|
||||||
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
|
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
if (ResponseCache.TryGetValue(props.MessageId, out var value))
|
}
|
||||||
|
catch
|
||||||
{
|
{
|
||||||
response = Encoding.UTF8.GetString(value);
|
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"),
|
||||||
ResponseCache.Remove(props.MessageId);
|
SimApiUtil.JsonOption);
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+48
-54
@@ -1,14 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Threading;
|
||||||
using System.Text.Encodings.Web;
|
using System.Threading.Tasks;
|
||||||
using System.Text.Json;
|
|
||||||
using System.Text.Json.Serialization;
|
|
||||||
using System.Text.Unicode;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using RabbitMQ.Client.Events;
|
using MQTTnet;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
@@ -20,74 +18,70 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
private void RunRpcServer()
|
private void RunRpcServer()
|
||||||
{
|
{
|
||||||
RpcServerChannel = CreateChannel(Options.RpcProcessorNum, "RpcServer");
|
var rsTopicPrefix = $"{Options.SysName}/{Options.AppName}/rpc/server/";
|
||||||
var queue = $"{Options.SysName}_{Options.AppName}_server";
|
var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
var router = $"server.{Options.AppName}";
|
.WithTopicFilter(o =>
|
||||||
RpcServerChannel.QueueDeclare(queue, true, false, true, null);
|
o.WithTopic($"$queue/{rsTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
||||||
RpcServerChannel.QueueBind(queue, Options.SysName, router, null);
|
.Build();
|
||||||
var consumer = new EventingBasicConsumer(RpcServerChannel);
|
Client.ApplicationMessageReceivedAsync += e =>
|
||||||
consumer.Received += (ch, ea) =>
|
|
||||||
{
|
{
|
||||||
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
|
if (!e.ApplicationMessage.Topic.StartsWith(rsTopicPrefix)) return Task.CompletedTask;
|
||||||
Logger.LogDebug(
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
"RPC Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
var action = e.ApplicationMessage.Topic.Replace(rsTopicPrefix, string.Empty);
|
||||||
ea.BasicProperties.MessageId, ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, Options.AppName,
|
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
||||||
|
logger.LogDebug(
|
||||||
|
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
||||||
|
e.ApplicationMessage.ContentType, appInfo[0], action, Options.AppName,
|
||||||
reqBody);
|
reqBody);
|
||||||
var res = new SimApiBaseResponse(404, "method not found");
|
var res = new SimApiBaseResponse(404, "method not found");
|
||||||
var method = RpcRegistry.FirstOrDefault(x => x.Key == ea.BasicProperties.Type);
|
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
||||||
if (method != null)
|
if (method == null) return Task.CompletedTask;
|
||||||
{
|
|
||||||
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
|
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
|
||||||
var mt = callClass.GetType().GetMethod(method.Method);
|
var mt = callClass.GetType().GetMethod(method.Method);
|
||||||
var param = Array.Empty<object>();
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var pt = mt.GetParameters()[0].ParameterType;
|
var pt = mt!.GetParameters()[0].ParameterType;
|
||||||
if (pt == typeof(string))
|
var param = pt == typeof(string)
|
||||||
{
|
? [reqBody]
|
||||||
param = new[] { reqBody };
|
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption);
|
|
||||||
param = new[] { paramObj };
|
|
||||||
}
|
|
||||||
var ret = mt.Invoke(callClass, param);
|
var ret = mt.Invoke(callClass, param);
|
||||||
res = new SimApiBaseResponse<object>(ret);
|
res = new SimApiBaseResponse<object>
|
||||||
|
{
|
||||||
|
Data = ret
|
||||||
|
};
|
||||||
}
|
}
|
||||||
catch (TargetInvocationException e)
|
catch (TargetInvocationException ex)
|
||||||
{
|
{
|
||||||
if (e.InnerException is SimApiException ie)
|
if (ex.InnerException is SimApiException ie)
|
||||||
{
|
{
|
||||||
Logger.LogDebug("RPC调用错误: {Err}", ie.Message);
|
logger.LogDebug("Synapse RPC调用错误: {Err}", ie.Message);
|
||||||
res = new SimApiBaseResponse(ie.Code, ie.Message);
|
res = new SimApiBaseResponse(ie.Code, ie.Message);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
res = new SimApiBaseResponse(500, e.Message);
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Logger.LogDebug("RPC调用失败: {Err}", e.Message);
|
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
|
||||||
res = new SimApiBaseResponse(500, e.Message);
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
||||||
var reply = $"client.{ea.BasicProperties.ReplyTo}.{ea.BasicProperties.AppId}";
|
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{e.ApplicationMessage.ContentType}";
|
||||||
var props = RpcServerChannel.CreateBasicProperties();
|
var message = new MqttApplicationMessageBuilder()
|
||||||
props.AppId = Options.AppId;
|
.WithTopic(reply)
|
||||||
props.CorrelationId = ea.BasicProperties.MessageId;
|
.WithPayload(returnJson)
|
||||||
props.MessageId = Guid.NewGuid().ToString();
|
.WithRetainFlag(false)
|
||||||
props.ReplyTo = Options.AppName;
|
.Build();
|
||||||
props.Type = ea.BasicProperties.Type;
|
if (!Client!.IsConnected) return Task.CompletedTask;
|
||||||
RpcServerChannel.BasicPublish(Options.SysName, reply, false, props, Encoding.UTF8.GetBytes(returnJson));
|
Client!.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
Logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Rpc Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
||||||
ea.BasicProperties.MessageId, ea.BasicProperties.Type, Options.AppName, ea.BasicProperties.ReplyTo,
|
e.ApplicationMessage.ContentType, action, Options.AppName, appInfo[0], returnJson);
|
||||||
returnJson);
|
|
||||||
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
RpcServerChannel.BasicConsume(queue, true, "", false, false, null, consumer);
|
Client.SubscribeAsync(rsSubOpts).Wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+58
-93
@@ -3,83 +3,71 @@ using System.Collections.Generic;
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using RabbitMQ.Client;
|
using MQTTnet;
|
||||||
using RabbitMQ.Client.Exceptions;
|
using MQTTnet.Client;
|
||||||
|
using MQTTnet.Formatter;
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Configs;
|
using SimApi.Configurations;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
|
||||||
{
|
{
|
||||||
private IServiceProvider Sp { get; }
|
private IServiceProvider Sp { get; } = sp;
|
||||||
|
|
||||||
private SimApiSynapseOptions Options { get; }
|
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
||||||
|
|
||||||
private ILogger<Synapse> Logger { get; }
|
private MqttFactory MqttFactory { get; } = new();
|
||||||
|
public IMqttClient Client { get; set; }
|
||||||
private IConnection Connection { get; set; }
|
|
||||||
|
|
||||||
private IModel EventClientChannel { get; set; }
|
|
||||||
|
|
||||||
private IModel EventServerChannel { get; set; }
|
|
||||||
|
|
||||||
private IModel RpcClientChannel { get; set; }
|
|
||||||
|
|
||||||
private IModel RpcServerChannel { get; set; }
|
|
||||||
|
|
||||||
private List<RegisterItem> EventRegistry { get; set; }
|
private List<RegisterItem> EventRegistry { get; set; }
|
||||||
|
|
||||||
private List<RegisterItem> RpcRegistry { get; set; }
|
private List<RegisterItem> RpcRegistry { get; set; }
|
||||||
|
|
||||||
public Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
|
|
||||||
{
|
|
||||||
Logger = logger;
|
|
||||||
Sp = sp;
|
|
||||||
Options = simApiOptions.SimApiSynapseOptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Init()
|
public void Init()
|
||||||
{
|
{
|
||||||
ProcessAttribute();
|
ProcessAttribute();
|
||||||
Logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
|
logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
|
||||||
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
|
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
|
||||||
{
|
{
|
||||||
Logger.LogCritical("Synapse初始化失败: AppName or SysName 错误");
|
logger.LogCritical("Synapse初始化失败: AppName 和 SysName 不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
Options.AppId ??= Guid.NewGuid().ToString();
|
Options.AppId ??= Guid.NewGuid().ToString();
|
||||||
Logger.LogInformation("System Name: {SysName}\nApp Name: {AppName}\nAppId: {AppId}", Options.SysName,
|
logger.LogInformation("Synapse Sys Name: {SysName}\nSynapse App Name: {AppName}\nSynapse App Id: {AppId}",
|
||||||
Options.AppName, Options.AppId);
|
Options.SysName, Options.AppName, Options.AppId);
|
||||||
CreateConnection();
|
CreateConnection();
|
||||||
CheckAndCreateExchange();
|
|
||||||
//事件客户端
|
//事件客户端
|
||||||
if (Options.DisableEventClient)
|
if (Options.DisableEventClient)
|
||||||
{
|
{
|
||||||
Logger.LogWarning("Event Client Disabled: DisableEventClient set true");
|
logger.LogWarning("Synapse Event Client Disabled: DisableEventClient set true");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
RunEventClient();
|
logger.LogInformation("Synapse Event Client Ready");
|
||||||
Logger.LogInformation("Event Client Ready");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//RPC客户端
|
//RPC客户端
|
||||||
if (Options.DisableRpcClient)
|
if (Options.DisableRpcClient)
|
||||||
{
|
{
|
||||||
Logger.LogWarning("Rpc Client Disabled: DisableEventClient set true");
|
logger.LogWarning("Synapse Rpc Client Disabled: DisableEventClient set true");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
RunRpcClient();
|
RunRpcClient();
|
||||||
Logger.LogInformation("Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
|
logger.LogInformation("Synapse Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (RpcRegistry.Count > 0)
|
if (RpcRegistry.Count > 0)
|
||||||
{
|
{
|
||||||
RunRpcServer();
|
RunRpcServer();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (EventRegistry.Count > 0)
|
if (EventRegistry.Count > 0)
|
||||||
{
|
{
|
||||||
RunEventServer();
|
RunEventServer();
|
||||||
@@ -89,16 +77,17 @@ public partial class Synapse
|
|||||||
|
|
||||||
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param)
|
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param)
|
||||||
{
|
{
|
||||||
var res = new SimApiBaseResponse(500, "Rpc Client Disabled!");
|
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
||||||
if (Options.DisableRpcClient)
|
if (Options.DisableRpcClient)
|
||||||
{
|
{
|
||||||
Logger.LogError("Rpc Client Disabled!");
|
logger.LogError("Synapse Rpc Client Disabled!");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var data = FireRpc(appName, method, param);
|
var data = FireRpc(appName, method, param);
|
||||||
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
||||||
}
|
}
|
||||||
|
|
||||||
return res as SimApiBaseResponse<T>;
|
return res as SimApiBaseResponse<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +100,7 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
if (Options.DisableEventClient)
|
if (Options.DisableEventClient)
|
||||||
{
|
{
|
||||||
Logger.LogError("Event Client Disabled!");
|
logger.LogError("Synapse Event Client Disabled!");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -121,70 +110,43 @@ public partial class Synapse
|
|||||||
|
|
||||||
private void CreateConnection()
|
private void CreateConnection()
|
||||||
{
|
{
|
||||||
var factory = new ConnectionFactory
|
Client = MqttFactory.CreateMqttClient();
|
||||||
|
var clientOpts = new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)
|
||||||
|
.WithWebSocketServer(o => o.WithUri(Options.Websocket))
|
||||||
|
.WithCredentials(Options.Username, Options.Password)
|
||||||
|
.WithClientId($"{Options.AppName}:{Options.AppId}")
|
||||||
|
.Build();
|
||||||
|
Client!.ConnectAsync(clientOpts, CancellationToken.None).Wait();
|
||||||
|
Client.ConnectedAsync += _ =>
|
||||||
{
|
{
|
||||||
HostName = Options.MqHost,
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
|
||||||
Port = Options.MqPort,
|
return Task.CompletedTask;
|
||||||
VirtualHost = Options.MqVHost,
|
|
||||||
UserName = Options.MqUser,
|
|
||||||
Password = Options.MqPass
|
|
||||||
};
|
};
|
||||||
|
//重连
|
||||||
|
Client.DisconnectedAsync += async _ =>
|
||||||
|
{
|
||||||
|
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 断开连接,开始重连...", Options.AppName, Options.AppId);
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Connection = factory.CreateConnection();
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 开始连接MQTT服务器...", Options.AppName, Options.AppId);
|
||||||
Logger.LogInformation("连接RabbitMQ服务器成功");
|
Client.ConnectAsync(clientOpts).Wait();
|
||||||
}
|
}
|
||||||
catch (BrokerUnreachableException e)
|
catch
|
||||||
{
|
{
|
||||||
Logger.LogError("连接RabbitMQ失败: \n{Err}", e);
|
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 重连失败...", Options.AppName, Options.AppId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
private IModel CreateChannel(ushort processNum = 0, string desc = "unknow")
|
|
||||||
{
|
|
||||||
IModel channel = null;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var log = $"Channel [{desc}] 创建成功...";
|
|
||||||
channel = Connection.CreateModel();
|
|
||||||
if (processNum != 0)
|
|
||||||
{
|
|
||||||
channel.BasicQos(0, processNum, false);
|
|
||||||
log += $"最大处理器数量: {processNum}";
|
|
||||||
}
|
|
||||||
Logger.LogInformation(log);
|
|
||||||
}
|
|
||||||
catch (ConnectFailureException e)
|
|
||||||
{
|
|
||||||
Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e);
|
|
||||||
}
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void CheckAndCreateExchange()
|
|
||||||
{
|
|
||||||
var channel = CreateChannel(0, "Exchange");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
channel.ExchangeDeclare(Options.SysName, ExchangeType.Topic, true, true, null);
|
|
||||||
Logger.LogDebug("Register Exchange Success");
|
|
||||||
}
|
|
||||||
catch (ConnectFailureException e)
|
|
||||||
{
|
|
||||||
Logger.LogError("Failed to declare Exchange.\n {Err}", e);
|
|
||||||
}
|
|
||||||
channel.Close();
|
|
||||||
Logger.LogDebug("Exchange Channel Closed");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ProcessAttribute()
|
private void ProcessAttribute()
|
||||||
{
|
{
|
||||||
EventRegistry = new List<RegisterItem>();
|
EventRegistry = [];
|
||||||
RpcRegistry = new List<RegisterItem>();
|
RpcRegistry = [];
|
||||||
var stackTrace = new StackTrace();
|
var stackTrace = new StackTrace();
|
||||||
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod();
|
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
||||||
var assembly = callingMethod.DeclaringType.Assembly;
|
var assembly = callingMethod?.DeclaringType?.Assembly;
|
||||||
var types = assembly.GetTypes(); // 获取程序集中的所有类型
|
var types = assembly!.GetTypes(); // 获取程序集中的所有类型
|
||||||
foreach (var type in types)
|
foreach (var type in types)
|
||||||
{
|
{
|
||||||
var methods = type.GetMethods(); // 获取类型中的所有方法
|
var methods = type.GetMethods(); // 获取类型中的所有方法
|
||||||
@@ -204,6 +166,7 @@ public partial class Synapse
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
|
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
|
||||||
{
|
{
|
||||||
var attribute =
|
var attribute =
|
||||||
@@ -220,19 +183,21 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var events = EventRegistry.Aggregate(string.Empty,
|
var events = EventRegistry.Aggregate(string.Empty,
|
||||||
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
|
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
|
||||||
var rpcList = RpcRegistry.Aggregate(string.Empty,
|
var rpcList = RpcRegistry.Aggregate(string.Empty,
|
||||||
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
|
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
|
||||||
Logger.LogInformation(">>> Synapse System 读取Event方法:{Event}\n>>>Synapse System 读取RPC方法:{Rpc}", events, rpcList);
|
if (EventRegistry.Count > 0) logger.LogInformation(">>> Synapse System 读取Event方法:{Event}", events);
|
||||||
|
if (RpcRegistry.Count > 0) logger.LogInformation(">>> Synapse System 读取RPC方法:{Rpc}", rpcList);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class RegisterItem
|
public class RegisterItem
|
||||||
{
|
{
|
||||||
public string Key { get; set; }
|
public string Key { get; init; }
|
||||||
|
|
||||||
public Type Class { get; set; }
|
public Type Class { get; init; }
|
||||||
|
|
||||||
public string Method { get; set; }
|
public string Method { get; init; }
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user