【问题标题】:.NET SignalR Error: Cannot read property 'client' of undefined.NET SignalR 错误:无法读取未定义的属性“客户端”
【发布时间】:2018-04-18 02:41:30
【问题描述】:

我目前正在尝试在 .NET Web 应用程序中使用 SignalR。在查看了许多帖子/文章后,我仍然感到困惑。在页面加载时,我收到一个错误:

Uncaught TypeError: Cannot read property 'client' of undefined

我目前的实现如下:

BundleConfig.cs:

//note jquery is rendered in a shared bundle in _layout.cshtml. I have
//verified in Chrome debugger it is loaded before the bundles shown here
bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
                  "~/Scripts/jquery.signalR-2.2.3.js"));

bundles.Add(new ScriptBundle("~/bundles/home")
        .Include("~/Scripts/Home/Index.js"));

在视图中呈现的捆绑包:

@section scripts {
     @Scripts.Render("~/bundles/signalr")
     @Scripts.Render("~/bundles/home")
}

Startup.cs:

public void Configuration(IAppBuilder app)
{
  app.MapSignalR();
}

DashboardHub.cs:

namespace Sample.SignalR
{
  [HubName("dashboardHub")]
  public class DashboardHub : Hub
  {
    public void sendMessage(string message)
    {
      Clients.All.receiveMessage(notes);
    }
  }
}

Index.js:

$(function () {
    var messageHub = $.connection.dashboardHub;

    //send message to hub so hub updates other clients
    $(document).on("submit", "#messageForm", function () {
        messageHub.server.sendMessage($("#Message").val());
    });

    //receive message
    messageHub.client.receiveMessage= function (message) {  
        $("#Message").empty();
        $("#Message").text(notes);
    }

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

在线脚本中页面加载时抛出错误:

messageHub.client.receiveNotesUpdate = function (notes) {

我已经检查并仔细检查了一些事情:

  • 脚本以正确的顺序呈现在页面上
  • 客户端和服务器之间的集线器名称和方法名称匹配(已尝试使用 并且没有[HubName("dashboardHub")] 注释)
  • 集线器类是公开的

我不确定为什么 messageHub 在这一点上是未定义的。我该如何解决这个问题?

【问题讨论】:

    标签: .net asp.net-mvc signalr signalr.client


    【解决方案1】:

    我认为您错过了添加自动生成的 SignalR Hub 脚本

    <script src="signalr/hubs"></script>
    

    就我而言,我的信号器集线器位于 webapi 上。我包括了我的 api 所在的域:

    <script src="somedomainorinstance/signalr/hubs"></script>
    

    同样在您的页面加载时,您可以添加它以查看是否正在建立连接

    $.connection.hub.url = url + "/signalr/hubs";
    $.connection.hub.logging = true;
    $.connection.hub.start()
        .done(function () { console.log("Signal R connected"); })
        .fail(function () { console.log("Could not Connect to signal R hub!"); });
    
    //I added this to established the connection again in case of a disconnect
    $.connection.hub.disconnected(function () {
        setTimeout(function () {
            $.connection.hub.start();
        }, 5000); // Re-start connection after 5 seconds
    });
    
    //put the rest of your code here
    

    这就是我现在的设置方式。它运行良好。

    我希望这会有所帮助!干杯!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多