Implementing Azure SignalR in Serverless Mode: A Practical Guide
Saad Ullah
Tech Enthusiast | Software Engineer | Azure | C# | .NET | Blazor | Angular | Docker | SQL | Typescript | Javascript
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:
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
Implementation Steps
Step 1: Setting Up Azure SignalR
Step 2: Create an Azure Function App
{ "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
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!
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!
Software Developer | React Developer | JavaScript Developer | MERN STACK | WordPress Developer
1 个月nice work, appreciated ??
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