【问题标题】:How to create Hub Proxy using AspNetCore SignalR如何使用 AspNetCore SignalR 创建集线器代理
【发布时间】:2018-09-29 03:51:27
【问题描述】:

有人知道 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();
});

【问题讨论】:

    标签: c# asp.net-core signalr


    【解决方案1】:

    添加 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();
    

    您可以使用不同的方法来执行异步任务。

    注意:您的 Hub 还应该使用 SignalR 的 .Net Core 包 (Microsoft.AspNetCore.SignalR) 才能使其正常工作(根据我的经验)。

    【讨论】:

    • 我已经更改了我在 Startup.cs 文件中配置的 URL。现在看起来像这样:withUrl("localhost:64017/scan")。但是当我调用该方法时没有任何反应。它不应该从我的集线器调用方法吗?还是来自 javascript 文件?
    • 没关系。另一个问题是为什么它不调用 Hub 方法。您的答案完美无缺。非常感谢!
    • 很高兴能帮上忙!
    • @LukeVillanueva,它会向所有客户发送消息吗?我已经尝试以相同的方式在这里显示,我可以找到连接 ID 和连接状态。但是,js代码根本没有收到。这是我的问题:stackoverflow.com/q/59840085/4753489
    猜你喜欢
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 2016-04-23
    相关资源
    最近更新 更多