I have troubles to get my ASP.NET Core SignalR app working.
I have this server-side code :
public class PopcornHub : Hub
{
private int Users;
public async Task BroadcastNumberOfUsers(int nbUser)
{
await Clients.All.InvokeAsync("OnUserConnected", nbUser);
}
public override async Task OnConnectedAsync()
{
Users++;
await BroadcastNumberOfUsers(Users);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
Users--;
await BroadcastNumberOfUsers(Users);
await base.OnDisconnectedAsync(exception);
}
}
whose SignalR Hub service is configured as :
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSignalR();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseSignalR(routes =>
{
routes.MapHub<PopcornHub>("popcorn");
});
...
}
In my client-side (WPF app), I have a service :
public class PopcornHubService : IPopcornHubService
{
private readonly HubConnection _connection;
public PopcornHubService()
{
_connection = new HubConnectionBuilder()
.WithUrl($"{Utils.Constants.PopcornApi.Replace("/api", "/popcorn")}")
.Build();
_connection.On<int>("OnUserConnected", (message) =>
{
});
}
public async Task Start()
{
await _connection.StartAsync();
}
}
My issue is that, when I call Start() method, I get the exception "Cannot start a connection that is not in the Initial state". The issue occurs either locally or in Azure.
The SignalR endpoint is fine but no connection can be established. What am I missing?
You seem to be trying to start a connection that has already been started. Also note that as of alpha2 the connection is not restartable - i.e. if it is stopped you cannot restart it - you need to create a new connection.
EDIT
In post alpha2 versions the connection will be restartable.