我目前正在尝试在.NET网络应用中使用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
未定义。我该如何解决这个问题?
答案 0 :(得分:2)
我认为您错过了添加自动生成的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
这就是我现在的设置方式。它工作得很好。
我希望这有帮助!干杯!