Search code examples
c#asp.net-coresignalr

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();
});

Solution

  • 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;
    
    object[] myData = { notificationmessag.Title, notificationmessag.Content };
    
    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).