Route To Take With SqlDependency OnChange(更改时使用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)。比较每个版本here和here。
您应该从IHubContext获取上下文,并将其连接起来,如here所示:
public class HomeController : Controller
{
private readonly IHubContext<NotificationHub> _hubContext;
public HomeController(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
}
根据文档,IHubContext可以在以下情况下使用:
现在,要连接客户端,您可以选择正确的技术(javascript、typescript等)。可以在以下位置找到示例(来自Microsoft Docs):IHubContext用于向客户端发送通知,不用于调用集线器上的方法。
"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的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更改时使用SqlDependency的路线


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01