简体   繁体   中英

Show real time database changes on browser using Signalr, asp.net Core and sql dependency injection

Hi I am very new to SignalR and asp.net core and my underlying problem is that I want a user to be able to see changes that are made to the database in realtime. I have an example of working code with signalr and the asp.net framework, but when I try to convert it to asp core it fails because of my hub. I'm pretty sure the problem is very straight forward but some of the other examples on the net are just out of my current depth.

cushub.cs:

public class CusHub : Hub
    {
        public static void Show()
        {
           //The below code is what doesn't work in aspcore. This is what i'm struggling with.
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CusHub>();
            context.Clients.All.displayCustomer();
        }
    }

customercontroller.cs

public JsonResult Get()
{

    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(@"SELECT [Id],[CustId],[CustName] FROM [dbo].[ad.signalr] WHERE [Status] <> 0", connection))
        {
            command.Notification = null;

            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

            if (connection.State == ConnectionState.Closed)
                connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            var listCus = reader.Cast<IDataRecord>()
                    .Select(x => new
                    {
                        Id = (int)x["Id"],
                        CusId = (string)x["CustId"],
                        CusName = (string)x["CustName"],
                    }).ToList();

            return Json(new { listCus = listCus });

        }
    }
}

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
    CusHub.Show();
}

customer view

@Html.Hidden("Get", Url.Action("Get", "Customer"))

<table class="table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Customer Id</th>
            <th>Customer Name</th>
        </tr>
    </thead>

    <tbody id="tblInfo"></tbody>
</table>

signalr js file

$(function () {

    var cus = $.connection.cusHub;

    cus.client.displayCustomer = function () {
        getData();
    };

    $.connection.hub.start();
    getData();
});

function getData() {
    var $tbl = $('#tblInfo');
    $.ajax({
        url: $("#Get").val(),
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            $tbl.empty();

            $.each(data.listCus, function (i, model) {
                $tbl.append
                    (
                        '<tr>' +
                        '<td>' + model.Id + '</td>' +
                        '<td>' + model.CusId + '</td>' +
                        '<td>' + model.CusName + '</td>' +
                        '<tr>'
                    );
            });
        }
    });
}

The code doesn't throw any exceptions apart from in my hub. With the:

GlobalHost.ConnectionManager.GetHubContext<CusHub>()
context.Clients.All.displayCustomer();


Iclientproxy does not contain a definition for displayCustomer();

I know there have been some changes to signalrcore but is there an easy fix to get this up at running?

The above code works in asp.net framework

Thanks for your help

I assume you're using a Strongly typed hub if you have a displayCustomer() method. Check out the example in that documentation, which should put you on the right path. But here are a couple issues I see right away:

First, you'll need to change the declaration of CusHub to derive from Hub<T> where T is the interface you made to define the methods that your SignalR client will accept. So if that's called ICusHub , then you would have something like this:

public class CusHub : Hub<ICusHub>

Second, you don't need to get a context . It's already available in your Hub class. So all you need is this:

await Clients.All.displayCustomer();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM