在 .NET 控制台客户端应用程序中使用 ASP.NET Core SignalR 从 Azure SignalR 接收消息

Aar*_*ver 5 c# azure signalr.client asp.net-core-signalr azure-signalr

我正在学习 SignalR 但遇到了障碍。

我有一个 Azure 函数,已成功发布到 Azure SignalR 托管服务(在无服务器模式下配置)

我一直在关注这个快速入门:

快速入门:使用 C# 通过 Azure Functions 和 SignalR 服务创建聊天室

我想要实现的基本上是将来自服务器的消息接收到我的客户端应用程序中。为了原型化,我创建了一个控制台应用程序。

我添加了以下 Nuget 包

Microsoft.AspNetCore.SignalR.Client -版本 1.1.0 Microsoft.Azure.WebJobs.Extensions.SignalRService

所有基础设施似乎都工作正常 - 我的假设是我可以在以下地址运行演示网站,将其指向我的本地实例(或托管在 Azure 中的实例) https://azure- samples.github.io/signalr-service-quickstart-serverless-chat/demo/chat-v2/

我的 AzureFunction 发布的消息直接发布到聊天窗口中。

如何将这些消息打印到控制台?

using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using System;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.ReadKey();

            var connection = new HubConnectionBuilder().WithUrl("http://localhost:7071/api").Build();


            connection.On<SignalRMessage>("newMessage", (message) =>
            {
                Console.WriteLine(message.Arguments);
            });


            connection.On("newMessage", (string server, string message) =>
            {
                Console.WriteLine($"Message from server {server}: {message}");
            }
  );
            await connection.StartAsync();
            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我强烈怀疑我的问题与

连接.On<...>

声明。他们从不开火。Connection.StartAsync() 似乎工作正常并建立了与 Azure SignalR 实例的连接。

我是否遗漏了一些基本点?我现在只是在挣扎。

简而言之 - 有人可以给我一个指向我的控制台窗口接收和写入消息的指针 - 与网络聊天演示中消息打印到网络浏览器的方式非常相似(请参阅上面的第二个链接)。

这些消息是简单的广播消息,我想要发送给所有连接的客户端。

几乎所有示例都是用 Javascript 编写的。

提前致谢。

Aar*_*ver 3

当我发现如何向 SignalR 添加日志记录后,我发现它无法解析正在发送的类型。

一旦我更改了连接,它就起作用了。转到正确的类型,例如

connection.On<CorrectType>("newMessage", (message) =>
            {
                Console.WriteLine(message.stringproperty);
            });
Run Code Online (Sandbox Code Playgroud)

通过查看文章使用 Azure SignalR 服务进行 Azure Functions 开发和配置,我的想法被误导了

他们“看起来”(至少在我看来)向 SignalR 添加了一条“SignalRMessage”类型的消息。事实上,他们添加了“CorrectType”消息类型

CorrectType message
signalRMessages.AddAsync(
    new SignalRMessage
    {
        // the message will only be sent to these user IDs
        UserId = "userId1",
        Target = "newMessage",
        Arguments = new [] { message }
    });
Run Code Online (Sandbox Code Playgroud)