问题描述
我有一个signalR服务器,工作正常,并且一些客户端(前端页面)正确接收了来自服务器的消息或事件。
但是,现在客户端之一是Web api。但是我不确定如何进行相应的配置以实现Web api不断监听和接收来自服务器signalR的调用的目标。
注意:SignalR服务器和客户端在.Net Core上。
我一直在寻找这种情况,但我没有。
Microsoft提供的example是一种“相似”的示例,但这是Windows窗体。所以,我有点迷路。
任何人都对如何获得它有一些想法?我会感激的。
解决方法
我建议使用该Microsoft示例,但将其实现为后台服务。您只需使用SignalR.Client
包实现后台服务,然后在启动时运行即可。然后,您将有一个正在监听SignalR呼叫的服务。
services.AddHostedService<SignalRService>();
public sealed class SignalRService : BackgroundService
{
/// <summary>
/// Executes the background service.
/// </summary>
/// <param name="cancellationToken">
/// The cancellation token. This token signals that the background service is being stopped.
/// </param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>This method is automatically triggered after the background service is started.</remarks>
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
// your SignalR code
}
}