public async Task SendGroupMessageAsync(SendGroupMessageRequest req) { //发送消息一定不能写到Hub上,因为那样前端用户就能直接调用聊天服务器的Hub接口发送消息,就无法在应用层面做 //内容的过滤了,发送消息一定要通过应用的服务器端调用GroupController.SendGroupMessageAsync来做,这样在应用服务器端可以做干预 //Hub上通常只写获取消息等无潜在威胁或者不需要应用服务器处理的方法 string userId = this.HttpContext.User.GetUserId();//不能用this.Context.UserIdentifier,因为他是包含AppKey前缀的 string groupName = this.HttpContext.User.GetGroupName(req.toGroupId); string userDisplayName = this.HttpContext.User.GetUserDisplayName(); bool containsUserId; using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(redisSetting.Value.Configuration)) { IDatabase db = redis.GetDatabase(redisSetting.Value.DbId); containsUserId = await db.SetContainsAsync($"{groupName}_Members", userId); } //检查用户是否属于这一组 if (!containsUserId) { throw new HubException("UserId=" + userId + " not in group:" + req.toGroupId); } GroupMessageResp msg = new GroupMessageResp(); msg.Content = req.content; msg.DateTime = DateTime.Now; msg.FromUserDisplayName = userDisplayName; msg.FromUserId = userId; msg.ObjectName = req.objectName; msg.TargetGroupId = req.toGroupId; await this.Context.Clients.Group(groupName).SendAsync("OnGroupMessage", msg); using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(redisSetting.Value.Configuration)) { IDatabase db = redis.GetDatabase(redisSetting.Value.DbId); await db.ListLeftPushAsync($"{groupName}_Messages", msg.ToJsonString()); } }
public async Task SendGroupMessageAsync(SendGroupMessageRequest req) { //发送消息一定不能写到Hub上,因为那样前端用户就能直接调用聊天服务器的Hub接口发送消息,就无法在应用层面做 //内容的过滤了,发送消息一定要通过应用的服务器端调用GroupController.SendGroupMessageAsync来做,这样在应用服务器端可以做干预 //Hub上通常只写获取消息等无潜在威胁或者不需要应用服务器处理的方法 string userId = this.HttpContext.User.GetUserId();//不能用this.Context.UserIdentifier,因为他是包含AppKey前缀的 string groupName = this.HttpContext.User.GetGroupName(req.toGroupId); string userDisplayName = this.HttpContext.User.GetUserDisplayName(); bool containsUserId; IDatabase db = redis.GetDatabase(); containsUserId = await db.SetContainsAsync($"{groupName}_Members", userId); //检查用户是否属于这一组 if (!containsUserId) { throw new HubException("UserId=" + userId + " not in group:" + req.toGroupId); } GroupMessageResp msg = new GroupMessageResp(); msg.Id = Guid.NewGuid().ToString("N"); msg.Content = req.content; msg.DateTime = DateTime.Now; msg.FromUserDisplayName = userDisplayName; msg.FromUserId = userId; msg.ObjectName = req.objectName; msg.TargetGroupId = req.toGroupId; string msgJson = msg.ToJsonString(); await db.ListLeftPushAsync($"{groupName}_Messages", msgJson); await db.ListLeftPushAsync($"{groupName}_MessagesWaitToSent", msgJson); await db.SetAddAsync("AllGroupsName", groupName); }