且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将SignalR Chat保存到数据库

更新时间:2023-02-13 21:57:14

对于这个问题,我认为您应该将用户ID和连接ID保存到数据库中,并保存在该聊天中发送的消息。



请检查以下代码。

For this issue, I think you should save the user id and the connection id to your database as well as save the messages that are sent in that chat.

Just check below code.
public override System.Threading.Tasks.Task OnConnected()
    {
          // Get UserID. Assumed the user is logged before connecting to chat and userid is saved in session.
          string UserID = (string)HttpContext.Current.Session["userid"];

          // Get ChatHistory and call the client function. See below
          this.GetHistory(UserID); 

          // Get ConnID
          string ConnID =  Context.ConnectionId; 

          // Save them in DB. You got to create a DB class to handle this. (Optional)
          DB.UpdateConnID(UserID, ConnID); 
    }

    private void GetHistory(UserID)
    {
          // Get Chat History from DB. You got to create a DB class to handle this.
          string History = DB.GetChatHistory(UserID); 

          // Send Chat History to Client. You got to create chatHistory handler in Client side.
          Clients.Caller.chatHistory(History );           
    }

     // This method is to be called by Client 
    public void Chat(string Message)
    {
          // Get UserID. Assumed the user is logged before connecting to chat and userid is saved in session.
         string UserID = (string)HttpContext.Current.Session["userid"]; 

         // Save Chat in DB. You got to create a DB class to handle this
         DB.SaveChat(UserID, Message); 

         // Send Chat Message to All connected Clients. You got to create chatMessage handler in Client side.
         Clients.All.chatMessage(Message);  
    }



欲了解更多信息,请按照以下说明。



https:// github。 com / SignalR / SignalR / issues / 1214



希望有所帮助,谢谢。


For more information, please follow below.

https://github.com/SignalR/SignalR/issues/1214

Hope that helps, thanks.