Search code examples
azureazure-functionssignalrasp.net-core-signalr

Azure Function - Broadcast a message from an TimerTrigger to an Azure SignalR Service


All I'm hoping to do is Broadcast a message to all say every 5min.

I thought that the below would work but I need a connectionId and a connectionId is readonly.

I have looked at using LogicApps but those have no connector to SignalR. Every single example I've found looks at older, deprecated versions. I'd even happily assign a unique ConnectionId to my service if that was feasible.

    [FunctionName("SendMessage")]
    public static async Task RunAsync([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log)
    {
        HubConnection connection = new HubConnectionBuilder()
            .WithUrl(new Uri("http://localhost:5003/MessageHub"))
            .WithAutomaticReconnect()
            .Build();

        await connection.StartAsync();

        await connection.InvokeAsync("SendMessageToGroup", "Group2", "This is a test");
    }

Solution

  • Use this:

    var connection = new HubConnectionBuilder()
                    .WithUrl("http://localhost:5003/messagehub", options =>
                    {
                        options.Headers["Application"] = "API Sender";
                    })
                    .WithAutomaticReconnect()
                    .Build();
    
    await connection.StartAsync();
    await connection.SendAsync("SendNotification", "test");
    

    In your messagehub.cs, create this:

    public async Task SendNotification(string mensagem)
    {
        await Clients.All.SendAsync("ReceiveGenericEvent", mensagem, DateTime.Now.Ticks.ToString());
    }
    

    https://github.com/hgmauri/signalr-socket-dotnet5