【问题标题】:SignalR with web Api as client [.Net Core]SignalR 与 web Api 作为客户端 [.Net Core]
【发布时间】:2020-08-22 02:38:43
【问题描述】:
我有一个 signalR 服务器工作正常,一些客户端(前端页面)正确接收来自服务器的消息或事件。
但是,现在其中一个客户端是 Web api。但是我不确定如何进行相应的配置以达到web api不断监听和接收来自服务器signalR的调用的目标。
注意:SignalR 服务器和客户端位于 .Net Core 上。
我一直在寻找这种情况,但没有找到。
某种“类似”的例子是来自微软的example,但这是一个windows窗体。所以,我有点迷路了。
有人对如何获得它有一些想法吗?我会很感激的。
【问题讨论】:
标签:
.net-core
signalr
signalr.client
【解决方案1】:
我建议使用该 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
}
}