SignalR动态集线器名称

时间:2018-11-07 15:03:38

标签: javascript .net azure signalr azure-functions

我正在使用Azure功能从事件中心读取消息并将其发布到SignalR实例。我有连接到SignalR实例并正在接收消息的前端JavaScript。我想要的是根据传入的值动态设置Azure函数库中的“ HubName”属性。这很容易吗?我在下面包括了我的Azure函数调用。在这两种方法中,我都希望动态设置HubName值,该值硬编码为“ deviceMessages”

    public static SignalRConnectionInfo GetSignalRInfo(
        [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
        [SignalRConnectionInfo(HubName = "deviceMessages")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }


    public static Task SendMessage(
        [EventHubTrigger("{EventHubName}", Connection = "EventHubConnectionAppSetting")]string myEventHubMessage,
        [SignalR(HubName = "deviceMessages")] IAsyncCollector<SignalRMessage> signalRMessages)
    {
        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                Target = "newMessage",
                Arguments = new[] { myEventHubMessage }
            });
    }

2 个答案:

答案 0 :(得分:1)

您可以执行命令式绑定。在函数的签名中使用IBinder binder,然后可以在运行时创建绑定。

var signalRAttribute = new SignalRAttribute(/* your settings here */));
var outputMessages = await binder.BindAsync<IAsyncCollector<SignalRMessage>>(signalRAttribute);

这里也有很好的示例:

How do I use Binder to perform dynamic bindings in my C# Function?

在这里:

https://weblogs.asp.net/sfeldman/azure-functions-to-make-audit-queue-and-auditors-happy

答案 1 :(得分:1)

我通过使用SignalRConnectionInfo对象的UserId属性找到了解决此问题的另一种方法。我使用自定义标头字段在“协商”调用中传递了要接收消息的设备的ID,该ID返回该ID的令牌。然后,当从事件中心接收到消息时,我将在SignalRMessage对象中设置该值。这样,我所在的设备页面仅接收该特定设备正在发送的消息。

    [FunctionName("negotiate")]
    public static SignalRConnectionInfo GetSignalRInfo(
        [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
        [SignalRConnectionInfo(HubName = "deviceMessages", UserId = "{headers.deviceId}")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }

    [FunctionName("messages")]
    public static Task SendMessage(
        [EventHubTrigger("{EventHubName}", Connection = "EventHubConnectionAppSetting")]string myEventHubMessage,
        [SignalR(HubName = "deviceMessages")] IAsyncCollector<SignalRMessage> signalRMessages)
    {
        var dev = JToken.Parse(Convert.ToString(myEventHubMessage));
        DeviceMessage msg = dev.ToObject<DeviceMessage>();

        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                UserId = msg.deviceId,
                Target = "newMessage",
                Arguments = new[] { myEventHubMessage }
            });
    }