From ff846fe72f9e856d51368ceb93e4cf75b7c94e15 Mon Sep 17 00:00:00 2001 From: tanglong <842690096@qq.com> Date: Tue, 10 Jun 2025 16:32:54 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BA=BF=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WeChatApplet/Services/Impl/UserService.cs | 35 ++++++++++++++++------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/WeChatApplet/Services/Impl/UserService.cs b/WeChatApplet/Services/Impl/UserService.cs index 387c7e2..eb4d2ce 100644 --- a/WeChatApplet/Services/Impl/UserService.cs +++ b/WeChatApplet/Services/Impl/UserService.cs @@ -430,19 +430,33 @@ namespace YD_WeChatApplet.Services SchoolCode = userInfo.PhoneNo }); - var userAuth = await _userContext.User_Auth.CountAsync(x => x.Self_Id == userInfo.User_Id && x.Bind_Id == userInfo.User_Id); - if (userAuth == 0) + // 异步启动一个后台任务,执行数据库插入逻辑,不影响主流程 + _ = Task.Run(async () => { - await _userContext.User_Auth.AddAsync(new User_Auth() + try { - Self_Id = userInfo.User_Id, - Bind_Id = userInfo.User_Id, - Role_Id = userInfo.Role_Id, - Token = token - }); + var authCount = await _userContext.User_Auth + .CountAsync(x => x.Self_Id == userInfo.User_Id && x.Bind_Id == userInfo.User_Id); - await _userContext.SaveChangesAsync(); - } + if (authCount == 0) + { + await _userContext.User_Auth.AddAsync(new User_Auth() + { + Self_Id = userInfo.User_Id, + Bind_Id = userInfo.User_Id, + Role_Id = userInfo.Role_Id, + Token = token + }); + + await _userContext.SaveChangesAsync(); + } + } + catch (Exception ex) + { + // 记录异常,避免后台线程未捕获异常引发崩溃 + Console.WriteLine($"[UserAuth Insert Error]: {ex.Message}"); + } + }); return new UserInfoDto() { @@ -456,6 +470,7 @@ namespace YD_WeChatApplet.Services Token = token }; } + private async Task GetWeChatSession(string code) { string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={AppSettings.WeChat.Appid}&secret={AppSettings.WeChat.Secret}&js_code={code}&grant_type=authorization_code";