Reputation: 1258
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", "", "");
Upvotes: 17
Views: 16299
Reputation: 15234
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.
Upvotes: 17