SignalR主动通知订阅者示例

本文介绍了一个使用SignalR实现支付通知的示例。该示例包括客户端JavaScript代码与服务器端C#代码,通过实时通信机制实现支付状态更新后的即时通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html代码:

<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
<script>
    $(function () {
        var hub = $.connection.payHub;
        hub.client.waitNotify = function (tran, url) {
            console.log("waitNotify:" + tran + "   " + url);
            if (tran) {
                location.href = url;
            }

        };
        $.connection.hub.start().done(function () {
            console.log("hub done");
        });
    })
</script>

hub代码:

[HubName("payHub"), Authorize]
    public class payHub : Hub
    {
        public static Dictionary<Guid, string> userPayHub = new Dictionary<Guid, string>();
        public static void Notify(Guid userId, string redirectUrl)
        {
            if (userPayHub.ContainsKey(userId))
            {
                Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<Hubs.payHub>()
                   .Clients.Client(Hubs.payHub.userPayHub[userId])
                   .waitNotify(true, redirectUrl);
            }
        }
        public override Task OnConnected()
        {
            var uid = this.Context.User.Identity.GetUserId();
            userPayHub[uid] = this.Context.ConnectionId;
            return base.OnConnected();
        }
        public override Task OnDisconnected(bool stopCalled)
        {
            var uid = this.Context.User.Identity.GetUserId();
            userPayHub.Remove(uid);
            return base.OnDisconnected(stopCalled);
        }
        public override Task OnReconnected()
        {
            var uid = this.Context.User.Identity.GetUserId();
            userPayHub.Remove(uid);
            return base.OnReconnected();
        }
    }

通知调用Notify方法即可。

关键点:GlobalHost.ConnectionManager.GetHubContext

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值