Simple example of signalR not working

2019-04-08 14:14发布

问题:

Not able to get SignalR working in my machine (with IE9). On entering some text and clicking submit, the text is not getting listed as intended. Also, I would expect the list getting updated from multiple instances of browser and It does not happen. There is no error. Could anybody help here?

C#

namespace TestSignalR.Hubs
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    /// <summary>
    /// Summary description for ChatHub.
    /// </summary>
    public class ChatHub : SignalR.Hubs.Hub
    {
        public void TestMessage(string message)
        {
            Clients.writeMessage(message);
        }
    }
}

ASPX

<input type="text" name="txtInput" id="txtInput" />
<button id="btnSubmit">Submit</button>

<ul id="messages">
</ul>
<script type="text/javascript" src="SignalR/Hubs"></script>
<script type="text/javascript">
    $(document).ready(function (message) {
        var chat = $.connection.chatHub;

        chat.writeMessage = function (message) {
            $("#messages").append("<li>" + message + "</li>");
        };

        $("#btnSubmit").click(function () {
            var text = $("#txtInput").val();
            chat.testMessage(text);
        });

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

</script>

Master page has the references for the JQuery and SignalR files:-

<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>

回答1:

Today I was working with the same issue.

First you need to add an atribute to your Hub with the name, as following:

[HubName("chathub")]
public class ChatHub : SignalR.Hubs.Hub

The next to do is to change the order of your calls in the javascript. You need to do the connection next to instantiate the hub. So, the code will be as following:

$(document).ready(function (message) {
   var chat = $.connection.chatHub;

   $.connection.hub.start();

   chat.writeMessage = function (message) {
      $("#messages").append("<li>" + message + "</li>");
   };

    $("#btnSubmit").click(function () {
        var text = $("#txtInput").val();
        chat.testMessage(text);
    });        
 });

I hope it works for you.



回答2:

Please install the 1.0 version of SignalR from Nuget as well. From your script references it looks like you are using 0.5.2 and the latest supported version at the time of writing this post is 1.0. Please download Microsoft.AspNet.SignalR from Nuget



标签: signalr