我试图获得一个非常基本的SignalR示例,它基于Microsoft's tutorial和由Visual Studio创建的WeatherForecast.NET/ANGLE SPA作为基础,因为这是我以后想要使用SignalR的同一类型的项目.The entire source code is at GitHub.
It looks as if the handshake/negotiation works and a websocket connection is established - but no messages are flowing there. This is what the Chrome Developer Tools show:
我感觉我忽略了一些小问题,但我正在努力想知道它可能是什么.
我从调整Program.cs
文件开始,这是相关代码:
builder.Services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
});
var app = builder.Build();
...
app.UseCors();
//app.MapHub<ProgressHub>("/progressHub");
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ProgressHub>("/progresshub"); // Map the hub URL here
});
app.Run();
请注意,MS建议使用app.MapHub<ProgressHub>("/progressHub");
,但SOM资源建议使用app.UseEndpoints
.这似乎没有什么不同.此外,我try 使用app.UseWebSockets();
,但这也没有改变任何事情.此外,我还确保启用了CORS.
这是我添加的控制器方法,它应该在SignalR通道上发送消息:
[HttpPost("startProcess")]
public async Task<IActionResult> StartProcess()
{
// Some logic to start the long-running process
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
// Report progress to the client
await _hubContext.Clients.All.SendAsync("ReceiveProgressUpdate", $"Step {i + 1} completed.");
}
return Ok("[]");
}
单步执行代码时,不会引发任何异常,代码运行时没有任何问题.在ANGLE客户端,我安装了SignalR包并创建了一个服务:
export class SignalRService {
private hubConnection: HubConnection;
private progressSubject: Subject<string> = new Subject<string>();
constructor() {
this.hubConnection = new HubConnectionBuilder()
.withUrl('https://localhost:44429/progresshub')
.build();
this.hubConnection.on('ReceiveProgressUpdate', (progressMessage: string) => {
this.progressSubject.next(progressMessage);
});
this.hubConnection.start().catch(err => console.error(err));
}
getProgressUpdates() {
return this.progressSubject.asObservable();
}
}
现在,我在我的SignalR组件中使用了该服务,但ProgressUpdates数组仍然为空:
export class SignalRComponent implements OnInit {
progressUpdates: string[] = [];
_httpClient: HttpClient;
constructor(private httpClient: HttpClient, private signalRService: SignalRService) {
this._httpClient = httpClient;
}
ngOnInit() {
this.signalRService.getProgressUpdates().subscribe((progressMessage: string) => {
this.progressUpdates.push(progressMessage);
});
}
startProcess() {
this.httpClient.post('https://localhost:44429/weatherforecast/startProcess', {}).subscribe();
}
}
Also, I have turned on the WebSocket Protocol in Windows as this was suggested on SO as well: