更改时使用SqlDependency的路线 [英] Route To Take With SqlDependency OnChange

查看:43
本文介绍了更改时使用SqlDependency的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将实时更新集成到我的ASP.NET WebAPI中,可以说是碰壁了。我已经设置了我的应用程序(在前端使用ANGLE),所以当页面最初加载时,它会从我的SQL数据库发出一个GET请求,然后网页就会用这些数据加载。此数据更改非常频繁,我希望合并实时更新。我将后端设置为使用SqlDependency在数据库发生更改时通知我,但是我不知道从哪里开始。我试图让SignalR与SqlDependency的OnChange事件处理程序一起工作,但我在网上没有看到太多关于这方面的内容。然后,我想使用角度并尝试轮询可能会更容易,但是我也不知道如何将其与我的OnChange事件处理程序结合起来。关于在服务器和客户端之间通信数据库已更改的最简单方式,您有什么建议吗?

推荐答案

您可以使用类似SignalR的WebSocket技术。它有三种风格:ASP.NET SignalR、ASP.NET Core SignalR和Azure SignalR(以Azure为主干的SignalR)。比较每个版本herehere

您应该从IHubContext获取上下文,并将其连接起来,如here所示:

public class HomeController : Controller
{
    private readonly IHubContext<NotificationHub> _hubContext;

    public HomeController(IHubContext<NotificationHub> hubContext)
    {
        _hubContext = hubContext;
    }
}

根据文档,IHubContext可以在以下情况下使用:

IHubContext用于向客户端发送通知,不用于调用集线器上的方法。

现在,要连接客户端,您可以选择正确的技术(javascripttypescript等)。可以在以下位置找到示例(来自Microsoft Docs):

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("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.
    li.textContent = `${user} says ${message}`;
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

也可以提到Socket.IO,我个人以前从来没有用过。

快乐编码

这篇关于更改时使用SqlDependency的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆