我无法让我的 ASP.NET Core SignalR 应用程序正常工作。
我有这个服务器端代码:
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);
}
}
其 SignalR Hub 服务配置为:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSignalR();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseSignalR(routes =>
{
routes.MapHub<PopcornHub>("popcorn");
});
...
}
在我的客户端(WPF 应用程序)中,我有一项服务:
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();
}
}
我的问题是,当我调用 Start() 方法时,出现异常“无法启动未处于初始状态的连接”。该问题发生在本地或 Azure 中。
SignalR 端点很好,但无法建立连接。我错过了什么?