我是新手,在asp.net mvc项目中使用signalr来捕获用户通知。我跟着these steps
这是我的ajax电话
$(function () {
// Proxy created on the fly
var job = $.connection.ntfHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
toastr.warning("1 Bildirim Alındı!");
getData();
};
// Start the connection
$.connection.hub.start().done(function () {
console.log("connection started")
getData();
}).fail(function (e) {
alert(e);
});
});
function getData() {
var tbl = $("#header_notification_bar")
$.ajax({
url: '@Url.Action("GetNtf","Home")',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
console.log("called");
}).error(function () {
});
}
这是我的SQL查询
SELECT
[nu].[NtU_ID], [n].[Ntf_Title], [n].[Ntf_Description],
[u].[Usr_NameSurname], [n].[Ntf_Date]
FROM
[dbo].[SysNotificationUser] nu
INNER JOIN
[dbo].[SysUser] u ON [nu].[NtU_UserID] = [u].[ID]
INNER JOIN
[dbo].[SysNotifications] n ON [nu].[NtU_NtfID] = [n].[Ntf_ID]
WHERE
[nu].[NtU_UserID] = 2
AND [nu].[NtU_IsRead] = 0
关于使用信号器如启动类的其他问题与教程中的相同。
有一些奇怪的情况第一次发生变化时ajax发出1个电话但其他变化ajax电话变得越来越大。除第一次以外,它不会进行1次更改。例如在控制台中,第一次只有一个“被叫”,但之后就像8次被“召唤”16次“被叫”等等。
在存储库中
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
NtfHub.Show();
}
}
和Hub类
public void Hello()
{
Clients.All.hello();
}
[HubMethodName("show")]
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NtfHub>();
context.Clients.All.displayStatus();
}
执行命令的方法
public List<PopulateNtfBar> GetData()
{
DataTable dt = new DataTable();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [NtU_ID] FROM [dbo].[SysNotificationUser] WHERE [NtU_UserID] =2 AND [NtU_IsRead] = 0", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += dependency_OnChange;
if (connection.State == ConnectionState.Closed)
connection.Open();
command.ExecuteScalar();
}
using (SqlCommand command2 = new SqlCommand(@"SELECT [nu].[NtU_ID],[n].[Ntf_Title],[n].[Ntf_Description],[u].[Usr_NameSurname],[n].[Ntf_Date] FROM [dbo].[SysNotificationUser] nu INNER JOIN [dbo].[SysUser] u ON [nu].[NtU_UserID]=[u].[ID] INNER JOIN [dbo].[SysNotifications] n ON [nu].[NtU_NtfID]=[n].[Ntf_ID] WHERE [nu].[NtU_UserID] =2 AND [nu].[NtU_IsRead] = 0", connection))
{
using (var reader = command2.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(item => new PopulateNtfBar()
{
Description = item["Ntf_Description"].ToString(),
Title = item["Ntf_Title"].ToString(),
TimeDiff = FindDifferenceTime(Convert.ToDateTime(item["Ntf_Date"]))
}).ToList();
}
}
}