SignalR(无服务器).NET 控制台客户端未收到消息

时间:2021-05-22 23:07:35

标签: azure azure-functions signalr signalr.client

我正在尝试通过创建一个示例 .NET 控制台应用程序来学习 SignalR,该应用程序通过托管的 Azure 函数应用程序通过无服务器 SignalR 接收消息;我一直在关注本教程 https://www.nikouusitalo.com/blog/qr-code-pings-with-azure-functions-and-azure-signalr/,但即使我建立了连接,在 Postman 中针对给定的 Azure 函数运行 POST 请求时,我也从未收到任何消息。这就是我所拥有的:

Azure 函数

    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            [SignalR(HubName = "QRCodeRehash")] IAsyncCollector<SignalRMessage> signalRMessages,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            await signalRMessages.AddAsync(
                new SignalRMessage
                {
                    Target = "pingQR",
                    Arguments = new[] { "ping" }
                });

            var responseMessage = "Success";

            return new OkObjectResult(responseMessage);
        }

        [FunctionName("negotiate")]
        public static SignalRConnectionInfo GetOrderNotificationsSignalRInfo(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
            [SignalRConnectionInfo(HubName = "QRCodeRehash")] SignalRConnectionInfo connectionInfo)
        {
            return connectionInfo;
        }
    }

.NET 控制台应用程序接收消息

        public class SignalRConnection
        {
            public async void Start()
            {
                var url = "https://sample.azurewebsites.net/api";

                var connection = new HubConnectionBuilder()
                    .WithUrl(url)
                    .WithAutomaticReconnect()
                    .Build();

                // receive a message from the hub
                connection.On<string, string>("pingQR", (user, message) => OnReceiveMessage(user, message));

                await connection.StartAsync();
            }

            private void OnReceiveMessage(string user, string message)
            {
                Console.WriteLine($"{user}: {message}");
            }

        }

按照教程的步骤,我只是在 Postman 中调用 Function1:

Postman

我总是得到“200 OK”,并且在 Azure 函数中也可以看到日志;此外,协商工作正常,因为它似乎每次都连接到 SignalR:

Azure logstream

我在 Azure 函数应用程序中设置了 CORS 以在我让它工作时允许任何事情:

Azure function CORS

非常感谢您的帮助;对于教程的所有者来说,它的工作方式很奇怪,但是,也许我最后需要做的事情被遗漏了,所以任何想法都将受到高度赞赏。

非常感谢!

更新:感谢@Brennan 的评论,我的错误在于提供的参数数量与客户端连接中详述的参数数量不同。它现在按预期工作。

0 个答案:

没有答案