gpt4 book ai didi

c# - SignalR HubConnection 未从无服务器 Azure SignalR 服务接收消息

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:26 24 4
gpt4 key购买 nike

我已在无服务器模式下创建了 Azure SignalR 服务。我在 Azure 函数应用程序中有一套函数来管理必须包含组的聊天服务。发布 Function App 时,我将 AzureSignalRConnectionString 设置为 SignalR 服务中 Keys 设置下的设置。我已在 Azure 门户中仔细检查连接字符串是否存在且正确。

我可以使用 Postman 成功调用 Azure 中的各个函数,并且可以在 Azure 门户中对此进行监控并查看日志消息等。

但是,如果我在客户端中使用 HubConnection 尝试调用函数,它不会到达那里。此外,Postman 成功发送的消息不会导致集线器触发接收。

因此可以看到以下使用 REST 接口(interface)的调用是从 Azure 门户执行的:

await client.PostAsync($"{baseUrl}/api/{group}/add/{userName}", new StringContent(string.Empty));

但是,使用 HubConnection 的以下调用不会触发相同的 Azure 函数:

await hubConnection.SendAsync("AddToGroup", group, userName);

其函数绑定(bind)是:

[FunctionName("AddToGroup")]
public static async Task<IActionResult> Run(
[HttpTrigger(
AuthorizationLevel.Anonymous,
"post",
Route = "{groupName}/add/{userId}")]
HttpRequest req,
string groupName,
string userId,
[SignalR(HubName = Constants.HubName)]
IAsyncCollector<SignalRGroupAction> signalRGroupActions,
ILogger log)
{
log.LogInformation("AddToGroup invoked");

await signalRGroupActions.AddAsync(
new SignalRGroupAction
{
UserId = userId,
GroupName = groupName,
Action = GroupAction.Add
});

return new OkObjectResult("All done");
}

函数应用程序包含一个协商函数,用于初始化集线器连接,如下所示:

var negotiateJson = await client.GetStringAsync($"{baseUrl}/api/negotiate");
var info = JsonConvert.DeserializeObject<NegotiateInfo>(negotiateJson);
hubConnection = new HubConnectionBuilder()
.WithUrl(info.Url, options =>
{
options.AccessTokenProvider = () => Task.FromResult(info.AccessToken);
})
.Build();

调试显示网址正确并且存在访问 token 。

我使用的是 Microsoft.AspNetCore.SignalR.Client V3.0.0,并遵循了许多指南和示例,但无法让 Azure SignalR 中心正常工作。

(我过去曾使用过托管 SignalR,发现它非常简单,但之前没有使用过 Azure 服务或 Azure Functions)。

我将永远感激任何帮助或指导。

谢谢

最佳答案

Azure SignalR 服务 + Azure Functions 支持通过 SignalR 从客户端向服务发送消息(使用 ASP.NET CORE)

服务器端(传统模型):

[FunctionName("notifyServerViaSignalR")]
public async Task NotifyServerViaSignalR([SignalRTrigger("YourHub", "messages", "NotifyServerViaSignalR")]
InvocationContext invocationContext, [SignalRParameter] string additionalParameter, ILogger logger)
{
logger.LogInformation($"Processed NotifyServerViaSignalR - AdditionalParameter:{additionalParameter} from ConnectionId:{invocationContext.ConnectionId}.");
}

同时在 Azure SignalR 设置中配置上游 URL

/runtime/webhooks/signalr?code=

Function_App_URL 可以在 Function App 的概述页面上找到,API_KEY 由 Azure Function 生成。您可以从 Function App 的应用 key 边栏选项卡中的 signalr_extension 获取 API_KEY。

客户端:

connection.invoke("NotifyServerViaSignalR",additionalParameter);

关于c# - SignalR HubConnection 未从无服务器 Azure SignalR 服务接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com