Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR 2.1.0: The connection has not been established

Tags:

c#

signalr

I have a ASP.NET Web Application with a simple HTML page and some JavaScript to communicate via SignalR. That works fine. Now I'm trying to call a method on the Hub from another project (in the same solution) and by using the .NET Signalr Client Api:

        var connection = new HubConnection("http://localhost:32986/");
        var hub = connection.CreateHubProxy("MessageHub");
        connection.Start();
        hub.Invoke("SendMessage", "", "");

The last line causes InvalidOperationException: The connection has not been established. But I am able to connect to the hub from my JavaScript code.

How can I connect to the Hub by using C# code?

UPDATE

The moment after writing this post, I tried to add .Wait() and it worked! So this will do:

        var connection = new HubConnection("http://localhost:32986/");
        var hub = connection.CreateHubProxy("MessageHub");
        connection.Start().Wait();
        hub.Invoke("SendMessage", "", "");
like image 679
Nicklas Møller Jepsen Avatar asked Jul 25 '14 21:07

Nicklas Møller Jepsen


Video Answer


1 Answers

HubConnection.Start returns a Task that needs to complete before you can invoke a method.

The two ways to do this are to use await if you are in an async method, or to use Task.Wait() if you are in a non-async method:

public async Task StartConnection()
{
    var connection = new HubConnection("http://localhost:32986/");
    var hub = connection.CreateHubProxy("MessageHub");
    await connection.Start();
    await hub.Invoke("SendMessage", "", "");
    // ...
}

// or

public void StartConnection()
{
    var connection = new HubConnection("http://localhost:32986/");
    var hub = connection.CreateHubProxy("MessageHub");
    connection.Start().Wait();
    hub.Invoke("SendMessage", "", "").Wait();
    // ...
}

The "How to establish a connection" section of the ASP.NET SignalR Hubs API Guide for the .NET client. goes into even more detail.

like image 92
halter73 Avatar answered Sep 20 '22 15:09

halter73