从服务器端发送到客户端时,SignalR消息不起作用

时间:2014-07-18 15:04:13

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

这是我的HTML:

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var chat = $.connection.khaosHub;

        // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (message) {
            // Html encode display name and message.
            var encodedMsg = $('<div />').text(message).html(); 
            // Add the message to the page.
            $('#discussion').append('<li>' + encodedMsg + '</li>');
        };

        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                console.log("sending");
                // Call the Send method on the hub.
                chat.server.send("something");
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        });
    });
</script>

我的中心:

public class KhaosHub : Hub
{
    public void Send(string message)
    {
        Clients.All.broadcastMessage(message);
    }
}

当我点击#sendmessage Send中的KhaosHub方法被触发时,我已使用断点进行验证,并且我的消息会通过broadcastMessage发送给div。< / p>

注意:我在上面的例子中没有收到我对app.MapSignalR的电话,因为我知道它在客户端工作。

我遇到的问题是,当我从某些后端代码中调用broadcastMessage时,它无法正常工作。我通过以下方式调用它:

var context = GlobalHost.ConnectionManager.GetHubContext<KhaosHub>();
context.Clients.All.broadcastMessage("some message");

当我调试Clients.All属性时,我无法看到任何客户(我不知道我是否应该能够,但我认为我会添加该信息。

有什么想法吗?

编辑:这是我的集线器启动类:

[assembly: OwinStartup(typeof (Startup))]

namespace CC.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

感谢您的提问。继续发表评论后,我追踪到了我自己的问题,也没有从GlobalHost.ConnectionManager获取正确的hubcontext。

为了解决这个问题,我在GlobalHost上专门设置了DependencyResolver,并将此Resolver传递给用于MapSignalR的HubConfiguration。

在以下代码中:

Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver = 
    New Microsoft.AspNet.SignalR.DefaultDependencyResolver

app.MapSignalR(
    New Microsoft.AspNet.SignalR.HubConfiguration With
    {.Resolver = Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver})

您可能希望将此VB.Net代码转换为C#。