【问题标题】:SignalR updates notification after a forced page refreshSignalR 在强制页面刷新后更新通知
【发布时间】:2022-01-08 17:35:48
【问题描述】:

我在我的 ASP.NET Core MVC 项目中使用 signalR 向用户推送通知。 我研究了类似的问题here,但它的解决方案并没有解决我的问题。我使用了以下 Javascript/jQuery 参考:

<script type="text/javascript" src="../../js/UserPage/jquery-3.6.0.min.js"></script>
<script src="~/microsoft/signalr/dist/browser/signalr.js"></script>
<script src="~/js/message.js"></script>

message.js如下:

var connection = new signalR.HubConnectionBuilder().withUrl("/Home/Messages").withAutomaticReconnect().build();
connection.start();

if (document.getElementById("sendBtn") != null) {
    document.getElementById("sendBtn").addEventListener("click", function () {
        var costCenter = $("#cost-center").val();
        connection.invoke("SendMessage", costCenter).catch(function (err) {
            return console.error(err);
        });
    });
}

集线器代码:

public class MessageHub : Hub
{
    //Dependency injections
    private readonly IUserRepository _userRepository;
    private readonly ICostCenterRepository _costcenterRepository;
    private readonly IHttpContextAccessor _httpContext;

    public MessageHub(IUserRepository userRepository, ICostCenterRepository costcenterRepository, IHttpContextAccessor httpContext)
    {
        _userRepository = userRepository;
        _costcenterRepository = costcenterRepository;
        _httpContext = httpContext;
    }
    public async Task SendMessage(string costCenter)
    {
        var HttpContext = _httpContext.HttpContext;
        string userId = _userRepository.GetUserIdByCostCenter(costCenter).ToString();
        string sender = HttpContext.Session.GetString("department");
        await Clients.User(userId).SendAsync("ReceiveMessage", sender);
    }
}

并且,主页中的javascript代码是:

<script>
    $(document).ready(function(){
            connection.on("ReceiveMessage", function (param) {
            if($('#badge-count').length){
                var currentMessageNum = parseInt($('#badge-count').text());
                $('#badge-count').text(currentMessageNum + 1);
                $('.main-msg-list').prepend('<li><a class="dropdown-item message-item" style="font-family: vazir !important" asp-controller="Messages" asp-action="Index" href="" id="msg-'+ currentMessageNum + 1 +'">پیام جدید از '+ param +'</a></li>');
            }else{
                $('#badge-count').text('1');
            }
        });
    });
</script>

问题是通知在强制刷新后更新。之后,通知工作正常并立即更新。我该如何解决?

【问题讨论】:

  • 如果在js中设置断点,在强制刷新之前页面加载时会调用js吗?

标签: javascript jquery asp.net-mvc asp.net-core signalr


【解决方案1】:

我通过对 Hub 代码进行一些更改来解决此问题:

[Authorize]
public class MessageHub : Hub
{
    //Dependancy injections
    private readonly IUserRepository _userRepository;
    private readonly ICostCenterRepository _costcenterRepository;
    private readonly IHttpContextAccessor _httpContext;

    public MessageHub(IUserRepository userRepository, ICostCenterRepository costcenterRepository, IHttpContextAccessor httpContext)
    {
        _userRepository = userRepository;
        _costcenterRepository = costcenterRepository;
        _httpContext = httpContext;
    }
    //define a dictionary to store the userid.
    private static Dictionary<string, List<string>> NtoIdMappingTable = new Dictionary<string, List<string>>();

    public override async Task OnConnectedAsync()
    {
        var username = Context.User.Identity.Name;
        var userId = Context.UserIdentifier;
        List<string> userIds;

        //store the userid to the list.
        if (!NtoIdMappingTable.TryGetValue(username, out userIds))
        {
            userIds = new List<string>();
            userIds.Add(userId);

            NtoIdMappingTable.Add(username, userIds);
        }
        else
        {
            userIds.Add(userId);
        }

        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        var username = Context.User.Identity.Name;

        //remove userid from the List
        if (NtoIdMappingTable.ContainsKey(username))
        {
            NtoIdMappingTable.Remove(username);
        }
        await base.OnDisconnectedAsync(exception);
    }
    public async Task SendMessage(string costCenter)
    {
        var HttpContext = _httpContext.HttpContext;
        string username = _userRepository.GetUsernameByCostCenter(costCenter).ToString();
        var userId = NtoIdMappingTable.GetValueOrDefault(username);
        string sender = HttpContext.Session.GetString("department");
        await Clients.User(userId.FirstOrDefault()).SendAsync("ReceiveMessage", sender);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2014-10-22
    • 2021-10-28
    • 1970-01-01
    • 2013-01-18
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多