【问题标题】:How to live notification in MVC with SignalR?如何使用 SignalR 在 MVC 中实时通知?
【发布时间】:2018-10-04 07:57:09
【问题描述】:

我正在尝试使用 signalR 进行实时通知。我的项目在本地主机上运行。但是当我设置 webconfig 服务器端时,我没有看到我的通知。 (虽然我是用 signalR 做的)

当我运行 Chrome 的检查项目的“互联网”部分时,我看到请求没有下降。这个问题怎么解决?

ajax 代码;

 function updateNotification() {
            $('#notiContent').empty();
            $('#notiContent').append($('<li>Yükleniyor...</li>'));
            $.ajax({
                type: 'GET',
                datatype : JSON,
                contentType: 'application/json; charset=utf-8',
                url: '/notification/GetNotificationFlows',
                success: function (response) {
                    $('#notiContent').empty();
                    if (response.length  == 0) {
                        $('#notiContent').append($('<li>Data yok..</li>'));
                    }
                    $.each(response, function (index, value) {

                        $('#notiContent').append($('<li>Yeni kişi : ' + value.flowName + ' (' + value.flowPhone + ') eklendi.</li>'));
                    });
                },
                error: function (error) {
                    console.log(error);
                }
            })
        }

Global.asax;

 string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        SqlDependency.Start(con);
    }
    protected void Session_Start(object sender, EventArgs e)
    {
        NotificationComponent NC = new NotificationComponent();
        var currentTime = DateTime.Now;
        HttpContext.Current.Session["LastUpdated"] = currentTime;
        NC.RegisterNotification(currentTime);
    }
    protected void Application_End()
    {
        //here we will stop Sql Dependency
        SqlDependency.Stop(con);
    }
}

通知组件

public void RegisterNotification(DateTime currentTime)
    {
        string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
        string sqlCommand = @"SELECT [flowId],[flowName],[flowEMail],[flowPhone],[kaynakId] from [dbo].[flow] where [createDate] > @createDate";
        //you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency
        using (SqlConnection con = new SqlConnection(conStr))
        {
            SqlCommand cmd = new SqlCommand(sqlCommand, con);
            cmd.Parameters.AddWithValue("@createDate", currentTime);
            if (con.State != System.Data.ConnectionState.Open)
            {
                con.Open();
            }
            cmd.Notification = null;
            SqlDependency sqlDep = new SqlDependency(cmd);
            sqlDep.OnChange += sqlDep_OnChange;
            //we must have to execute the command here
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                // nothing need to add here now
            }
        }
    }

    void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SqlDependency sqlDep = sender as SqlDependency;
            sqlDep.OnChange -= sqlDep_OnChange;

            //from here we will send notification message to client
            var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
            notificationHub.Clients.All.notify("eklendi.");

            //re-register notification
            RegisterNotification(DateTime.Now);
        }
    }

    public List<flow> GetFlows(DateTime afterDate)
    {
        using (smartCMSEntities dc = new smartCMSEntities())
        {
            return dc.flow.Where(a => a.createDate > afterDate).OrderByDescending(a => a.createDate).ToList();
        }
    }

通知控制器

public JsonResult GetNotificationFlows()
    {
        var notificationRegisterTime = Session["LastUpdated"] != null ? Convert.ToDateTime(Session["LastUpdated"]) : DateTime.Now;
        NotificationComponent NC = new NotificationComponent();
        var list = NC.GetFlows(notificationRegisterTime);
        Session["LastUpdate"] = DateTime.Now;
        return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

通知中心

public class NotificationHub : Hub
{
    //public void Hello()
    //{
    //    Clients.All.hello();
    //}
}

SQL(用于 sql 依赖)

ALTER DATABASE [db_name] SET ENABLE_BROKER with rollback immediate;

【问题讨论】:

    标签: asp.net-mvc signalr asp.net-ajax global-asax sqldependency


    【解决方案1】:

    在 Hub 中创建函数时,我遇到了同样的问题。

    让我们说

       public class NotificationHub : Hub
        {
            public static void Send()
            {
    
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
                context.Clients.All.displayStatus();
            }
        }
    

    并在你的 html 中调用它

            function updateNotificationCount() {
                $('span.count').show();
                var count = 0;
                count = parseInt($('span.count').html()) || 0;
                count++;
                $('span.noti').css("color", "white");
            //    $('span.count').css({ "background-color": "red", "color": "white" });
                $('span.count').html(count);
    
            }
            // signalr js code for start hub and send receive notification
            var hub = $.connection.notificationHub;
    
            // Declare a function on the hub hub so the server can invoke it
            hub.client.displayStatus = function () {
    
                updateNotificationCount();
    
            };
    
            // Start the connection
            $.connection.hub.start();
    

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 2019-01-21
      • 1970-01-01
      • 2014-11-07
      • 2018-02-12
      • 2021-03-08
      相关资源
      最近更新 更多