Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Hub Proxy using AspNetCore SignalR

Anyone know the AspNetCore SignalR equivalent of this code from AspNet SignalR?

Task.Factory.StartNew(() =>
{
    ////  var clients = Hub.Clients<RealTimeNotificationHub>();
    var connection = new HubConnectionContext("https://demohouse.go.ro:96/");
    var notificationmessag = new AlertMessage();
    notificationmessag.Content = "New message from " + device.Name + " <b>" +
                                 text + " </b>";
    notificationmessag.Title = alertType.Name;
    var myHub = connection.CreateHubProxy("realTimeNotificationHub");
    connection.Start().Wait();
    object[] myData = { notificationmessag.Title, notificationmessag.Content };
    myHub.Invoke("sendMessage", myData).Wait();
    connection.Stop();
});
like image 777
M. Chris Avatar asked Sep 28 '18 07:09

M. Chris


People also ask

How do I add a class to hub SignalR?

Or you can also add SignalR to a project by opening the "Tools" | "Library Package Manager" | "Package Manager Console" and running the command: "install-package Microsoft. AspNet. SignalR". Now again add the SignalR class.

What is a hub in SignalR?

What is a SignalR hub. The SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by client. In the client code, you define methods that are called from the server.


1 Answers

Add Nuget package Microsoft.AspNetCore.SignalR.Client and try the below code. I took the liberty to use your data on your post and translate it to the .Net Core version.

//I'm not really sure how your HUB route is configured, but this is the usual approach.

var connection = new HubConnectionBuilder()
                .WithUrl("https://demohouse.go.ro:96/realTimeNotificationHub") //Make sure that the route is the same with your configured route for your HUB
                .Build();

var notificationmessag = new AlertMessage();
notificationmessag.Content = "New message from " + device.Name + " <b>" +
                                         text + " </b>";
notificationmessag.Title = alertType.Name;

connection.StartAsync().ContinueWith(task => {
    if (task.IsFaulted)
    {
        //Do something if the connection failed
    }
    else
    {
        //if connection is successfull, do something
        connection.InvokeAsync("sendMessage", myData);

    }).Wait();

You can use a different approach on executing async tasks.

Note: Your Hub should be also using the .Net Core package for SignalR (Microsoft.AspNetCore.SignalR) in order for this to work (based on my experience).

like image 82
Luke Villanueva Avatar answered Sep 19 '22 14:09

Luke Villanueva