控制台应用程序如何连接到 Azure SignalR 服务器以从我的 Web API 获取通知

How does a console app connect to Azure SignalR Server to get notifications from my Web API

我对我的控制台应用程序如何连接到 Azure SignalR Server 以接收我通过 ASP.NET Core Web API 应用程序发送的通知感到有点困惑。

在我的 API 的启动中,我做了需要做的事情:

services.AddSignalR().AddAzureSignalR();

app.UseAzureSignalR(routes =>
{
   routes.MapHub<NotificationHub>("/notifications");
});

AddAzureSignalR() 方法通过我在应用设置中定义的连接字符串连接到 Azure SignalR 服务器。

但正如我在许多示例中看​​到的那样,要连接到我的控制台应用程序,我需要执行以下操作:

var connectionBuilder = new HubConnectionBuilder()
   .WithUrl("http://localhost:5000/notifications")
   .Build();
await connectionBuilder.StartAsync();

connectionBuilder.On<string, string>("broadcastNotification", (name, message) =>
{
   Console.WriteLine($"Name: {name}, Message: {message}");
});

我的控制台应用程序通过我的 API 而不是直接连接到 Azure SignalR 服务器的原因是什么?安全还是设计?

What are the reasons that my console application connects to the Azure SignalR server through my API and not directly? Security or by design?

根据您的描述和代码,您似乎有一个 hub server 并与 Azure SignalR 服务集成。

在这种类似于this official example演示的场景中,您的 Azure SignalR 服务的服务模式将为 默认模式.在此模式下,您的应用程序作为典型的 ASP.NET 核心(或 ASP.NET)SignalR 应用程序工作,并且客户端需要像您一样连接中心服务器。

关于服务模式的更多信息以及如何选择正确的服务模式,请查看此文档:

https://docs.microsoft.com/en-us/azure/azure-signalr/concept-service-mode#choose-the-right-service-mode