Bladeren bron

SignalR 3

leiy 1 jaar geleden
bovenliggende
commit
5d9b5bbf13

+ 8 - 4
OASystem/OASystem.Api/Controllers/ClientHubController.cs

@@ -43,7 +43,7 @@ namespace OASystem.API.Controllers
         [HttpPost("SendAllUserMessage", Name = "SendAllUserMessage")]
         public async Task<IActionResult> SendAllUserMessage( string msg)
         {
-            await _hubContext.Clients.All.SendAsync("ReceiveMessage", msg);
+            await _hubContext.Clients.All.ReceiveMessage(msg);
             return Ok("Send Successful!");
         }
 
@@ -55,17 +55,21 @@ namespace OASystem.API.Controllers
         /// <param name="hubContext"></param>
         /// <returns></returns>
         [HttpPost("SendCustomUserMessage", Name = "SendCustomUserMessage")]
-        public async Task<IActionResult> SendCustomUserMessage(int userid,string date )
+        public async Task<IActionResult> SendCustomUserMessage(int userId,string date )
         {
             string connId = string.Empty;
 
-            UserModel user = UserStore.OnlineUser.Where(it => it.UserId == userid).FirstOrDefault();
+            UserModel user = UserStore.OnlineUser.Where(it => it.UserId == userId).FirstOrDefault();
             if (user != null)
             {
                 connId = user.ConnectionId;
             }
+            else
+            {
+                return Ok("Send Failed! User Not Online!");
+            }
 
-            await _hubContext.Clients.Client(connId).SendSystemToUser(date);
+            await _hubContext.Clients.Client(connId).ReceiveMessage(date);
             return Ok("Send Successful!");
         }
     }

+ 7 - 2
OASystem/OASystem.Api/OAMethodLib/JwtHelper.cs

@@ -1,11 +1,13 @@
 using Microsoft.AspNetCore.Authentication;
 using Microsoft.AspNetCore.Authentication.Cookies;
 using Microsoft.AspNetCore.Http;
+using NetTaste;
 using OASystem.API.OAMethodLib.JuHeAPI;
 using OASystem.Domain.Dtos.Business;
 using SqlSugar.Extensions;
 using System.IdentityModel.Tokens.Jwt;
 using System.Security.Claims;
+using static NPOI.HSSF.Util.HSSFColor;
 
 namespace OASystem.API.OAMethodLib
 {
@@ -37,7 +39,9 @@ namespace OASystem.API.OAMethodLib
                  */                
 
                 new Claim(JwtRegisteredClaimNames.Jti, tokenModel.UserId.ToString()),
-                new Claim(JwtRegisteredClaimNames.GivenName, tokenModel.UserName),
+                //new Claim(JwtRegisteredClaimNames.GivenName, tokenModel.UserName),
+                new Claim("UserName", tokenModel.UserName),
+                //new Claim("UserId", tokenModel.UserId.ToString()),
                 new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                 new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                 //这个就是过期时间,目前是过期7200秒,可自定义,注意JWT有自己的缓冲过期时间
@@ -88,13 +92,14 @@ namespace OASystem.API.OAMethodLib
                 try
                 {
                     jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
-                    jwtToken.Payload.TryGetValue(ClaimTypes.GivenName, out userName);
+                    jwtToken.Payload.TryGetValue("UserName", out userName);
                 }
                 catch (Exception e)
                 {
                     Console.WriteLine(e);
                     throw;
                 }
+
                 var tm = new TokenModelJwt
                 {
                     UserId = (jwtToken.Id).ObjToInt(),

+ 3 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/HubClients/IChatClient.cs

@@ -12,6 +12,9 @@
 
         Task SendCustomUserMessage(object message);
 
+
+        Task ReceiveMessage(object message);
+
         /// <summary>
         /// 发送消息给指定用户(系统)
         /// </summary>

+ 4 - 1
OASystem/OASystem.Api/OAMethodLib/SignalR/HubService/CommonService.cs

@@ -14,7 +14,10 @@
             return $"Hello {new Random().Next(0, 100)} {data} ";
         }
 
-
+        internal object ReceiveMessage(string data)
+        {
+            return $"{data}";
+        }
 
     }
 }

+ 7 - 6
OASystem/OASystem.Api/OAMethodLib/SignalR/Hubs/ChatHub.cs

@@ -77,8 +77,9 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
 
                         _logger.LogInformation($"Client ConnectionId=> [[{connId}]] UserId=> [[{tokenModelJwt.UserId}]] Already Connection Server!");
 
-                        Clients.All.SendAsync("GetOnlineResponse", $"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 上线");
+                        //Clients.All.SendAsync("GetOnlineResponse", $"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 上线");
 
+                        Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 已上线!"));
                         //
                     }
                 }
@@ -97,16 +98,16 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
         /// <returns></returns>
         public override Task OnDisconnectedAsync(Exception exception)
         {
-            var connid = Context.ConnectionId;
-            _logger.LogInformation($"Client ConnectionId=> [[{connid}]] Already Close Connection Server!");
-            var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connid);
-            int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connid);
+            var connId = Context.ConnectionId;
+            _logger.LogInformation($"Client ConnectionId=> [[{connId}]] Already Close Connection Server!");
+            var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connId);
+            int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connId);
             if (model != null)
             {
 
                 var onlineUser = UserStore.OnlineUser.FindAll(u => u.GroupName == model.GroupName);
 
-                Clients.Group(model.GroupName).SendAsync("GetDisconnectResponse", onlineUser);
+                Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[UserID=>{model.UserId} ConnectionId=> {model.ConnectionId} ] 已下线!"));
             }
             return base.OnDisconnectedAsync(exception);
         }