【问题标题】:SignalR not set up correctly?SignalR 设置不正确?
【发布时间】:2014-04-10 05:11:11
【问题描述】:

很明显,我搞砸了,但似乎我已经正确地遵循了文档,所以我要求提供一些见解。

我已经构建了一个简单的 ASP.NET MVC5 应用程序,我正在测试文件状态的异步通知。作为概念证明,我:

  • 从 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
        });
    };
});

在我的控制器中,我有这样的东西来测试通知:

    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'); });
    });

...现在正在到达断点。但是,我所有的变量都以未定义的形式返回......我将不得不玩这个。我认为这与我的大小写有关。

【问题讨论】:

    标签: c# asp.net-mvc signalr asp.net-mvc-5 signalr-hub


    【解决方案1】:

    你在哪里给$.connection.hub.start()打电话?这是在你定义$.connection.notificationHub.client.notify 之后调用的吗?

    如果您在开始连接之前没有定义您的客户端notify 回调,您将不会订阅NotificationHub。这可能就是为什么永远不会调用包含您对 $.pnotify 的调用的 notify 回调的原因。

    http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#establishconnection

    【讨论】:

    • 嗯...这与我正在查看的文档绝对不同。
    猜你喜欢
    • 2020-10-14
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多