如何使用AspNetCore SignalR创建集线器代理

时间:2018-09-28 07:51:30

标签: c# asp.net-core signalr

任何人都可以从AspNet SignalR知道与该代码等效的AspNetCore 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();
});

1 个答案:

答案 0 :(得分:2)

添加Nuget包Microsoft.AspNetCore.SignalR.Client并尝试以下代码。我有权使用您发布的数据并将其转换为.Net Core版本。

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

您可以使用其他方法执行异步任务。

注意:您的集线器还应使用SignalR的.Net Core软件包(Microsoft.AspNetCore.SignalR),以使其正常工作(根据我的经验)。