如何在页面刷新后保留信号器消息

问题描述 投票:0回答:1

我能够向所有客户端发送信号消息,但每当客户端页面刷新时,消息(li)就会从通知面板(ul)中消失。

我想将消息保留到指定日期。下面是我到目前为止的代码。

ctx.Members.Add(addThisMember);
            await ctx.SaveChangesAsync();
            notyf.Success("member successfully created.");
            await hCtx.Clients.All.SendAsync("ReceiveNotification", $"New Member added: {addThisMember.Fullname}");
            return RedirectToAction("Members");



        public class NotificationHub : Hub
    {
        public async Task SendNotification(string Message)
        {
            await Clients.All.SendAsync("ReceiveNotification", Message);

        }
    }


        var connection = new signalr.HubConnectionBuilder().withUrl("/NotificationHub").build();

    connection.on("ReceiveNotification", function (message) {
        // do whatever you want to do with `message`

        var li = document.createElement("li");
        document.getElementById("messagesList").appendChild(li);
        li.textContent = `${user} says ${message}`;
    });

connection.start().catch(function (err) {
    return console.error(err.toString());
});
    
asp.net-mvc signalr.client asp.net-core-signalr
1个回答
0
投票

您可以将消息保存在前端的本地存储或后端的数据库中。

前端和后端保存的区别。

1。如果我们不需要长期保存数据,那么我们可以将其保存在localStorage中。这是样品和测试结果。

"use strict";
...

window.onload = function () {
    if (connection == undefined || connection == "undefined") {
        console.log("not connect to signalr server");
        
    } else {
        if (connection._connectionState == "Connected") {
            //document.getElementById("sendButton").disabled = false;
            // load chat history messages
            for (var i = 0, len = localStorage.length; i < len; i++) {
                var key = localStorage.key(i);
                let seconds = Math.abs(new Date().getTime() - new Date(key).getTime()) / 1000;
                //Data over 15s is not loaded
                if (seconds <= 15) {
                    var value = localStorage[key];
                    var li = document.createElement("li");
                    document.getElementById("messagesList").appendChild(li);
                    // We can assign user-supplied strings to an element's textContent because it
                    // is not interpreted as markup. If you're assigning in any other way, you
                    // should be aware of possible script injection concerns.
                    var msg = value;
                    li.textContent = msg;
                }

            }
        }
    }
}


connection.on("Chat_ReceiveMessage", function (user, message) {
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    // We can assign user-supplied strings to an element's textContent because it
    // is not interpreted as markup. If you're assigning in any other way, you
    // should be aware of possible script injection concerns.
    var msg = `${user} says ${message}`;
    li.textContent = msg;

    localStorage.setItem(new Date(), msg)
});

测试结果

2。如果我们想长期保存数据,那么我们可以将其保存在数据库中。您可以参考示例代码来加载历史消息

© www.soinside.com 2019 - 2024. All rights reserved.