XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEExtension.NetCore.ServerInteractive

[DLL] Server interaction extension, including user identity verification and querying in conjunction with AutoConfig

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEExtension.NetCore.ServerInteractive

优化错误处理机制,提升代码一致性与性能

本次更新统一错误处理为抛出异常,重构 Error 方法并新增 CloseWithError,接口同步调整。服务类错误逻辑简化,部分 Console 输出优化。版本号升级至 1.1.2,提升整体性能与代码结构。

8c652e8
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

10 个文件 +48 -35
Modified XFEExtension.NetCore.ServerInteractive/Implements/CoreService/XFEServerCoreServiceBase.cs +6 -3
@@ -21,11 +21,14 @@ public abstract class XFEServerCoreServiceBase : IXFEServerCoreServiceBase
21 21 public ServerCoreReturnArgs ReturnArgs { get; set; }
22 22
23 23 /// <inheritdoc/>
24 public async Task Close(string message) => await ReturnArgs!.Args.ReplyAndClose(message);
24 public async Task Close(string message) => await ReturnArgs!.Close(message);
25 25
26 26 /// <inheritdoc/>
27 public void Error(string message, HttpStatusCode code = HttpStatusCode.BadRequest) => ReturnArgs?.Error(message, code);
27 public void OK() => ReturnArgs?.OK();
28 28
29 29 /// <inheritdoc/>
30 public void OK() => ReturnArgs?.Close(HttpStatusCode.OK);
30 public Task CloseWithError(string message, HttpStatusCode code) => ReturnArgs!.CloseWithError(message, code);
31
32 /// <inheritdoc/>
33 public ServerCoreReturnArgs Error(string message, HttpStatusCode code = HttpStatusCode.BadRequest, bool handled = false) => ReturnArgs!.Error(message, code, handled);
31 34 }
Modified XFEExtension.NetCore.ServerInteractive/Interfaces/CoreService/IXFEServerCoreServiceBase.cs +10 -2
@@ -1,7 +1,7 @@
1 1 using System.Net;
2 2 using XFEExtension.NetCore.ServerInteractive.Models.ServerModels;
3 using XFEExtension.NetCore.XFETransform.JsonConverter;
4 3 using XFEExtension.NetCore.ServerInteractive.Utilities.Server;
4 using XFEExtension.NetCore.XFETransform.JsonConverter;
5 5
6 6 namespace XFEExtension.NetCore.ServerInteractive.Interfaces.CoreService;
7 7
@@ -46,5 +46,13 @@ public interface IXFEServerCoreServiceBase
46 46 /// </summary>
47 47 /// <param name="message">要返回的错误信息</param>
48 48 /// <param name="code">HTTP 状态码</param>
49 void Error(string message, HttpStatusCode code = HttpStatusCode.InternalServerError);
49 Task CloseWithError(string message, HttpStatusCode code = HttpStatusCode.BadRequest);
50
51 /// <summary>
52 /// 以异常结束与客户端的通讯
53 /// </summary>
54 /// <param name="message"></param>
55 /// <param name="code"></param>
56 /// <param name="handled"></param>
57 ServerCoreReturnArgs Error(string message, HttpStatusCode code = HttpStatusCode.BadRequest, bool handled = false);
50 58 }
Modified XFEExtension.NetCore.ServerInteractive/Models/ServerModels/ServerCoreReturnArgs.cs +1 -1
@@ -41,7 +41,7 @@ public class ServerCoreReturnArgs : Exception
41 41 /// </summary>
42 42 /// <param name="message"></param>
43 43 /// <param name="code"></param>
44 public async Task Error(string message, HttpStatusCode code = HttpStatusCode.BadRequest)
44 public async Task CloseWithError(string message, HttpStatusCode code = HttpStatusCode.BadRequest)
45 45 {
46 46 ReturnMessage = message;
47 47 Handled = true;
Modified XFEExtension.NetCore.ServerInteractive/Utilities/Helpers/UserHelper.cs +3 -3
@@ -47,7 +47,7 @@ public static class UserHelper
47 47 if (!userInfo.Enable)
48 48 return UserOperateResult.UserDisabled;
49 49 user = userInfo;
50 Console.WriteLine($"({user.UserName})");
50 Console.Write($"({user.UserName})");
51 51 return UserOperateResult.Success;
52 52 }
53 53
@@ -120,7 +120,7 @@ public static class UserHelper
120 120 {
121 121 var result = GetUser(userName, password, userInfoList, out var user);
122 122 if (result != UserOperateResult.Success)
123 r.Error(OutPutResult(result), HttpStatusCode.Forbidden);
123 throw r.Error(OutPutResult(result), HttpStatusCode.Forbidden);
124 124 return user!;
125 125 }
126 126
@@ -215,7 +215,7 @@ public static class UserHelper
215 215 {
216 216 var result = ValidateUserPermission(sessionId, computerInfo, ipAddress, requiredPermissionLevel, encryptedUserLoginModels, userInfoList);
217 217 if (result != UserOperateResult.Success)
218 r.Error(OutPutResult(result), HttpStatusCode.Forbidden);
218 throw r.Error(OutPutResult(result), HttpStatusCode.Forbidden);
219 219 }
220 220
221 221 /// <summary>
Modified XFEExtension.NetCore.ServerInteractive/Utilities/Server/Services/CoreService/CoreLogService.cs +2 -2
@@ -24,8 +24,8 @@ public class CoreLogService : ServerCoreUserServiceBase
24 24 case "get_log":
25 25 Console.Write("获取服务器日志请求");
26 26 UserHelper.ValidatePermission(Json["session"], Json["computerInfo"], ReturnArgs.Args.ClientIP, GetPermission, GetEncryptedUserLoginModelFunction(), GetUserFunction(), ReturnArgs);
27 if (!DateTime.TryParse(Json["startDateTime"], out var startDatetime)) Error("起始日期格式不正确");
28 if (!DateTime.TryParse(Json["endDateTime"], out var endDatetime)) Error("结束日期格式不正确");
27 if (!DateTime.TryParse(Json["startDateTime"], out var startDatetime)) throw Error("起始日期格式不正确");
28 if (!DateTime.TryParse(Json["endDateTime"], out var endDatetime)) throw Error("结束日期格式不正确");
29 29 await Close(XFEConsole.XFEConsole.Log.Export(startDatetime, endDatetime));
30 30 break;
31 31 case "clear_log":
Modified XFEExtension.NetCore.ServerInteractive/Utilities/Server/Services/CoreService/EntryPointVerifyServer.cs +2 -2
@@ -18,12 +18,12 @@ public class EntryPointVerifyServer : ServerCoreVerifyServiceBase
18 18 if (ServerBaseProfile.BannedIPAddressList.Contains(e.ClientIP))
19 19 {
20 20 Console.WriteLine("-校验失败");
21 r.Error("您的已被封禁", HttpStatusCode.Forbidden);
21 throw r.Error("您的IP已被封禁", HttpStatusCode.Forbidden);
22 22 }
23 23 if (e.RequestURL?.Segments.Length < 2 || $"{e.RequestURL?.Segments[0]}{e.RequestURL?.Segments[1]}" != $"/{ServerBaseProfile.EntryPoint}" || e.RequestMethod != "POST")
24 24 {
25 25 Console.WriteLine("-校验失败");
26 r.Error("请求的API接口不正确", HttpStatusCode.BadGateway);
26 throw r.Error("请求的API接口不正确", HttpStatusCode.BadGateway);
27 27 }
28 28 Console.WriteLine("-校验通过");
29 29 return true;
Modified XFEExtension.NetCore.ServerInteractive/Utilities/Server/Services/CoreService/IpBannerService.cs +4 -4
@@ -33,9 +33,9 @@ public class IpBannerService : ServerCoreUserServiceBase
33 33 await Close(ServerBaseProfile.BannedIPAddressList.ToJson());
34 34 break;
35 35 case "add_bannedIp":
36 Console.WriteLine($"添加禁止的IP地址请求 添加:{Json["bannedIp"]}");
36 Console.Write($"添加禁止的IP地址请求 添加:{Json["bannedIp"]}");
37 37 UserHelper.ValidatePermission(Json["session"], Json["computerInfo"], ReturnArgs.Args.ClientIP, AddPermission, GetEncryptedUserLoginModelFunction(), GetUserFunction(), ReturnArgs);
38 if (Json["bannedIp"] is null) Error("无IP地址传入");
38 if (Json["bannedIp"] is null) throw Error("无IP地址传入");
39 39 ServerBaseProfile.BannedIPAddressList.Add(new()
40 40 {
41 41 IPAddress = Json["bannedIp"],
@@ -44,9 +44,9 @@ public class IpBannerService : ServerCoreUserServiceBase
44 44 OK();
45 45 break;
46 46 case "remove_bannedIp":
47 Console.WriteLine($"删除禁止的IP地址请求 移除:{Json["bannedIp"]}");
47 Console.Write($"删除禁止的IP地址请求 移除:{Json["bannedIp"]}");
48 48 UserHelper.ValidatePermission(Json["session"], Json["computerInfo"], ReturnArgs.Args.ClientIP, RemovePermission, GetEncryptedUserLoginModelFunction(), GetUserFunction(), ReturnArgs);
49 var targetIp = ServerBaseProfile.BannedIPAddressList.FirstOrDefault(ip => ip.IPAddress == Json["bannedIp"].ToString()) ?? throw ReturnArgs.Error("无IP地址传入", HttpStatusCode.BadRequest);
49 var targetIp = ServerBaseProfile.BannedIPAddressList.FirstOrDefault(ip => ip.IPAddress == Json["bannedIp"].ToString()) ?? throw Error("无IP地址传入", HttpStatusCode.BadRequest);
50 50 await Close(ServerBaseProfile.BannedIPAddressList.Remove(targetIp).ToString());
51 51 break;
52 52 default:
Modified XFEExtension.NetCore.ServerInteractive/Utilities/Server/Services/CoreService/UserLoginService.cs +5 -5
@@ -18,9 +18,9 @@ public class UserLoginService<T> : ServerCoreUserLoginServiceBase<T> where T : c
18 18 var account = Json["account"].ToString();
19 19 var password = Json["password"].ToString();
20 20 var computerInfo = Json["computerInfo"].ToString();
21 if (account.IsNullOrWhiteSpace()) Error("账户名不能为空");
22 if (password.IsNullOrWhiteSpace()) Error("登录密码不能为空");
23 if (computerInfo.IsNullOrWhiteSpace()) Error("电脑信息不能为空");
21 if (account.IsNullOrWhiteSpace()) throw Error("账户名不能为空");
22 if (password.IsNullOrWhiteSpace()) throw Error("登录密码不能为空");
23 if (computerInfo.IsNullOrWhiteSpace()) throw Error("电脑信息不能为空");
24 24 var user = UserHelper.GetUser(Json["account"], Json["password"], GetUserFunction(), ReturnArgs!);
25 25 Console.Write($"{account}({computerInfo[..10]}...)");
26 26 var userLoginList = GetEncryptedUserLoginModelFunction().Where(userLogin => userLogin.UserLoginModel.ComputerInfo == computerInfo);
@@ -50,12 +50,12 @@ public class UserLoginService<T> : ServerCoreUserLoginServiceBase<T> where T : c
50 50 };
51 51 AddEncryptedUserLoginModelFunction(userLogin);
52 52 Console.Write($"到期时间 {userLogin.UserLoginModel.EndDateTime}");
53 await ReturnArgs!.Args.ReplyAndClose(JsonSerializer.Serialize(new
53 await Close(JsonSerializer.Serialize(new
54 54 {
55 55 session = $"{user.ID}|{UserHelper.Encrypt(userLogin.Key, userLogin.UserLoginModel)}",
56 56 expireDate = userLogin.UserLoginModel.EndDateTime,
57 57 userInfo = LoginResultConvertFunction(user)
58 }, JsonSerializerOptions), HttpStatusCode.OK);
58 }, JsonSerializerOptions));
59 59 }
60 60 else
61 61 {
Modified XFEExtension.NetCore.ServerInteractive/Utilities/Server/Services/CoreService/UserReloginService.cs +11 -11
@@ -19,20 +19,20 @@ public class UserReloginService<T> : ServerCoreUserLoginServiceBase<T> where T :
19 19 var session = Regex.Unescape(Json["session"].ToString());
20 20 Console.Write(session[..10]);
21 21 var computerInfo = Json["computerInfo"].ToString();
22 if (session.IsNullOrWhiteSpace()) Error("Session值不能为空");
23 if (computerInfo.IsNullOrWhiteSpace()) Error("电脑信息不能为空");
22 if (session.IsNullOrWhiteSpace()) throw Error("Session值不能为空");
23 if (computerInfo.IsNullOrWhiteSpace()) throw Error("电脑信息不能为空");
24 24 var split = session.Split('|');
25 if (GetEncryptedUserLoginModelFunction().FirstOrDefault(user => user.UserLoginModel.UID == split[0]) is not EncryptedUserLoginModel encryptedUserLoginModel) throw ReturnArgs.Error("Session值不正确或已过期", HttpStatusCode.Forbidden);
26 if (encryptedUserLoginModel.UserLoginModel.ComputerInfo != computerInfo) Error("电脑信息不匹配");
25 if (GetEncryptedUserLoginModelFunction().FirstOrDefault(user => user.UserLoginModel.UID == split[0]) is not EncryptedUserLoginModel encryptedUserLoginModel) throw Error("Session值不正确或已过期", HttpStatusCode.Forbidden);
26 if (encryptedUserLoginModel.UserLoginModel.ComputerInfo != computerInfo) throw Error("电脑信息不匹配");
27 27 var userLoginModel = UserHelper.Decrypt<UserLoginModel>(encryptedUserLoginModel.Key, split[1]);
28 28 if (userLoginModel.UID.IsNullOrWhiteSpace() || userLoginModel.UID != encryptedUserLoginModel.UserLoginModel.UID)
29 Error("登录用户ID不匹配");
30 var user = UserHelper.GetUser(userLoginModel.UID, GetUserFunction()) ?? throw ReturnArgs.Error("用户ID未注册", HttpStatusCode.Forbidden);
31 if (userLoginModel.LastIPAddress != ReturnArgs.Args.ClientIP) Error("IP地址不匹配");
32 if (userLoginModel.LastIPAddress != encryptedUserLoginModel.UserLoginModel.LastIPAddress) Error("IP地址不匹配");
33 if (userLoginModel.EndDateTime < DateTime.Now) Error("登录已过期");
34 if (userLoginModel.EndDateTime != encryptedUserLoginModel.UserLoginModel.EndDateTime) Error("登录已过期");
35 if (userLoginModel.ComputerInfo != encryptedUserLoginModel.UserLoginModel.ComputerInfo) Error("电脑信息不匹配");
29 throw Error("登录用户ID不匹配");
30 var user = UserHelper.GetUser(userLoginModel.UID, GetUserFunction()) ?? throw Error("用户ID未注册", HttpStatusCode.Forbidden);
31 if (userLoginModel.LastIPAddress != ReturnArgs.Args.ClientIP) throw Error("IP地址不匹配");
32 if (userLoginModel.LastIPAddress != encryptedUserLoginModel.UserLoginModel.LastIPAddress) throw Error("IP地址不匹配");
33 if (userLoginModel.EndDateTime < DateTime.Now) throw Error("登录已过期");
34 if (userLoginModel.EndDateTime != encryptedUserLoginModel.UserLoginModel.EndDateTime) throw Error("登录已过期");
35 if (userLoginModel.ComputerInfo != encryptedUserLoginModel.UserLoginModel.ComputerInfo) throw Error("电脑信息不匹配");
36 36 await Close(JsonSerializer.Serialize(LoginResultConvertFunction(user), JsonSerializerOptions));
37 37 }
38 38 }
Modified XFEExtension.NetCore.ServerInteractive/XFEExtension.NetCore.ServerInteractive.csproj +4 -2
@@ -5,7 +5,7 @@
5 5 <ImplicitUsings>enable</ImplicitUsings>
6 6 <Nullable>enable</Nullable>
7 7 <GenerateDocumentationFile>True</GenerateDocumentationFile>
8 <Version>1.1.1</Version>
8 <Version>1.1.2</Version>
9 9 <Title>XFEExtension.NetCore.ServerInteractive</Title>
10 10 <RepositoryUrl>https://github.com/XFEstudio/XFEExtension.NetCore.ServerInteractive</RepositoryUrl>
11 11 <AnalysisLevel>latest</AnalysisLevel>
@@ -21,7 +21,9 @@
21 21 <PackageReleaseNotes>
22 22 ## 调整
23 23
24 现在已经全面完成基于对象的请求处理
24 优化错误处理机制,提升代码一致性与性能
25
26 本次更新统一错误处理为抛出异常,重构 Error 方法并新增 CloseWithError,接口同步调整。服务类错误逻辑简化,部分 Console 输出优化。版本号升级至 1.1.2,提升整体性能与代码结构。
25 27
26 28 ## 新增
27 29