SignalR refuses to work

2019-06-25 10:56发布

Global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteTable.Routes.MapConnection<myconnection>("echo", "echo/{*operation}");
}

myconnection.cs

    public class myconnection : PersistentConnection
    {
        protected override Task OnReceivedAsync(string clientId, string data)
        {
            // Broadcast data to all clients
            return Connection.Broadcast(data);
        }
    }

~/Pages/Messages.aspx

<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        var connection = $.connection('echo');

        connection.received(function (data) {
            $('#messages').append('<li>' + data + '</li>');
        });

        connection.start();

        $("#broadcast").click(function () {
            connection.send($('#msg').val());
        });
    });
</script>

<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />

<ul id="messages">
</ul>

ERROR:

SignalR: Connection must be started before data can be sent. Call .start() before .send()

What I tried so far:

<configuration>
   <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
        </modules>
    </system.webServer>
</configuration>

<script type="text/javascript" src='<%= ResolveClientUrl("~/signalr/hubs") %>'></script>

Both solutions (https://github.com/SignalR/SignalR/wiki/Faq) did not fix my issue. Any idea(s)? Thanks.

1条回答
不美不萌又怎样
2楼-- · 2019-06-25 11:45

Make sure that you properly configure the url to the echo script:

var connection = $.connection('<%= ResolveClientUrl("~/echo") %>');

Since you are inside the ~/Pages folder using echo is incorrect because your routing expects /echo or /appname/echo if the application is hosted inside a virtual directory.

查看更多
登录 后发表回答