Implementing Azure SignalR in Serverless Mode: A Practical Guide

Implementing Azure SignalR in Serverless Mode: A Practical Guide

Azure SignalR is a versatile service that supports real-time communication for applications. This post focuses on implementing Azure SignalR in serverless mode using Azure Functions and a Web API. We'll also touch upon SignalR service modes and provide a step-by-step guide.

Understanding Azure SignalR Modes

Azure SignalR offers three service modes:

  • Default Mode: A traditional approach where the SignalR server is hosted alongside the application. Suitable for scenarios where the server maintains persistent WebSocket connections.
  • Serverless Mode: Ideal for serverless architectures. Azure Functions handle SignalR messaging without hosting a SignalR server. The client connects via the negotiate endpoint, and the function app sends messages through Azure SignalR.
  • Classic Mode: The original hosting model, used for legacy applications that leverage Azure SignalR without modern serverless features.

Objective:

Enable real-time messaging for connected clients by leveraging Azure SignalR in serverless mode. The solution involves a Web API that calls an Azure Function app. The Azure Function app is responsible for managing and dispatching messages to either all connected clients or specific Azure AD users, ensuring efficient communication across the system.

Prerequisites

  1. An active Azure subscription.
  2. Azure SignalR Service created with Serverless Mode enabled.
  3. Visual Studio 2022 or later with Azure development workloads installed.
  4. Basic knowledge of Azure Functions and Web APIs.

Implementation Steps

Step 1: Setting Up Azure SignalR

  1. Create an Azure SignalR resource via the Azure portal.
  2. Set the service mode to Serverless during creation.
  3. Obtain the connection string from the SignalR resource's Keys blade.

Step 2: Create an Azure Function App

  1. Create a new Azure Function App project in Visual Studio.
  2. Select the .NET Isolated Worker Process runtime.
  3. Register the SignalR connection string in local.settings.json:

{ "AzureSignalRConnectionString": "<your_connection_string>" }        

Step 3: Register SignalR in Program.cs

In the Program.cs file of the Azure Function app, register the ServiceManager and SignalR Hub using IServiceHubContext:

services.AddSingleton<IServiceManager>(sp =>
{
    return (IServiceManager)new ServiceManagerBuilder()
        .WithOptions(o => o.ConnectionString = connectionString)
        .BuildServiceManager();
    });

   // Register IServiceHubContext for sending messages 
     services.AddSingleton<IServiceHubContext>(sp =>
    {
         var serviceManager = sp.GetRequiredService<IServiceManager>();
          
          return serviceManager
                .CreateHubContextAsync("HubName")
                .GetAwaiter()
                .GetResult();
});        

Step 4: Implement Negotiate Endpoint

Add an HTTP-triggered Azure Function to handle client negotiation:

 [Function("Negotiate")]
 public async Task<HttpResponseData> Negotiate(
 [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
 {    
        // get userId from httpRequest from parameter
         var accessToken = _serviceManager.GenerateClientAccessToken(hubName,       userId); 
         var hubConnection = new
         {
             url = _serviceManager.GetClientEndpoint(hubName),
             accessToken
         };
         var response = req.CreateResponse(HttpStatusCode.OK);
         await response.WriteAsJsonAsync(hubConnection);
         return response;
 }        

Step 5: Implementing Message Sending in Azure Function

Azure Functions can be used to send notifications to SignalR clients in serverless mode. Add a new HTTP-triggered function for sending messages:

public class SendMessageFunction
{
    private readonly IServiceHubContext _serviceHubContext;

    public SendMessageFunction(IServiceHubContext serviceHubContext)
    {
        _serviceHubContext = serviceHubContext;
    }

    [Function("SendMessage")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
    {
        var data = await JsonSerializer.DeserializeAsync<MessagePayload>(req.Body);

        if (data == null || string.IsNullOrEmpty(data.Message))
        {
            return req.CreateResponse(HttpStatusCode.BadRequest);
        }

        await _serviceHubContext.
                       Clients.All.SendAsync("ReceiveMessage", data.Message);

        return req.CreateResponse(HttpStatusCode.OK);
    }
}        
public class MessagePayload
{
    public string Message { get; set; }
}        

Step 6: Call Azure function inside Web API

Constructs an HTTP request to the Azure Function's Notify endpoint using the function URL and key.

The Azure Function processes the payload and sends the SignalR notification to connected clients.

This setup allows the Web API to serve as a bridge between your clients and Azure Function for managing SignalR notifications.

You need to add Azure Function details to configuration:

{
    "AzureFunction": 
    {
        "NotifyUrl": "https://<your_function_app>.azurewebsites.net/api/Notify",
        "FunctionKey": "<your_function_key>"
    }
}        

Step 7: Deploy and Test

  1. Deploy the Azure Function and Web API projects to Azure.
  2. Use tools like Postman to test the negotiate and notify endpoints.

Conclusion

This guide walks through a serverless SignalR implementation using Azure Functions and Web APIs. By leveraging Azure SignalR's serverless mode, you can create scalable real-time messaging systems without maintaining a SignalR server. This architecture is cost-effective and integrates seamlessly with modern cloud applications.

Have questions or feedback? Let me know in the comments!

Sabir Hafeez ?

Co-founder and CTO @ Nascent Innovations | .NET Core | ERP Consultant | Cloud Computing | MEAN/MERN Developer | POS Applications

3 周

Great breakdown of Azure SignalR service modes and a clear step-by-step guide on implementing it in serverless mode!

Haris Khan

Software Developer | React Developer | JavaScript Developer | MERN STACK | WordPress Developer

1 个月

nice work, appreciated ??

回复
Maaz Shaikh

Technical Team Lead | Software Solution Designer | Software Consultant | Senior .Net Full Stack Developer | Expertise in C#, .NET, Blazor, Angular, React JS, SQL, Typescript, Javascript, EF, Dapper

2 个月

Insightful

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了