很明显,我搞砸了,但看起来我已经正确地遵循了文档,所以我要求一些见解。
我构建了一个简单的 ASP.NET MVC5 应用程序,我正在测试文件状态的异步通知。作为概念证明 I:
- 从 NuGet 安装 SignalR
- 将脚本引用添加到我的布局页面
- 添加了对“~/signalr/hubs”的“脚本”引用
我像这样创建了一个新的 NotificationHub:
public class Notification
{
public MessageLevels Type { get; set; }
public string Message { get; set; }
public string Title { get; set; }
}
public enum MessageLevels
{
Success,
Info,
Notice,
Error
}
public class NotificationHub : Hub
{
public void Notify(Notification model)
{
Clients.Caller.notify(model);
}
}
在此之后,我将以下通知脚本添加到我的布局页面:
$(function() {
var messages = $.connection.notificationHub;
messages.client.notify = function(model) {
$.pnotify({
title: model.title,
text: model.message,
type: model.type
});
};
});
在我的 Controller 中,我有类似这样的东西来测试通知:
public ActionResult Index()
{
System.Threading.ThreadPool.QueueUserWorkItem(state => SendNotification());
return View();
}
private void SendNotification()
{
Thread.Sleep(3500);
var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
context.Clients.All
.Notify(new Notification
{
Message = "This is a test.",
Title = "Test Message",
Type = MessageLevels.Notice
});
}
当我运行它时,我会在我的网络浏览器中监视以下行:
$.pnotify({
...但是,我的断点从未达到。
有人可以指出我做错了什么吗?
更新:
根据 halter73 的回答,我将脚本更改为:
$(function() {
var connection = $.hubConnection();
var notificationHubProxy = connection.createHubProxy('notificationHub');
notificationHubProxy.on('notify', function(model) {
$.pnotify({
title: model.title,
text: model.message,
type: model.type
});
});
connection.start()
.done(function() { console.log('Now connected, connection ID=' + connection.id); })
.fail(function() { console.log('Could not connect'); });
});
...现在到达断点。但是,我所有的变量都以未定义的形式返回……我将不得不尝试一下。我希望这与我的资本化有关。
请您参考如下方法:
您在哪里调用 $.connection.hub.start()?这是在您定义 $.connection.notificationHub.client.notify 之后调用的吗?
如果您在开始连接之前没有定义您的客户端notify 回调,您将不会订阅NotificationHub。这可能就是为什么永远不会调用包含对 $.pnotify 的调用的 notify 回调。
