Rank them

Written by

in

How to Build Live Dashboards Using SPSignalR and .NET In modern web applications, the demand for real-time data visualization is higher than ever. Whether it is tracking stock prices, monitoring system metrics, or displaying live user activity, dashboards must update instantly without requiring a page refresh.

ASP.NET Core SignalR provides a powerful, high-performance solution for this, enabling bi-directional communication between client and server. By utilizing WebSockets, SignalR allows the server to push data updates to connected clients the moment that data changes.

This article guides you through building a live, updating dashboard using .NET and SignalR, covering backend hub configuration, data streaming, and client-side integration. 1. Understanding the Architecture

Real-time dashboards require a persistent connection. Instead of the client constantly polling the server for new data, SignalR establishes a long-lived connection, allowing the server to “push” updates.

SignalR Hub: The central hub in the .NET backend that handles client connections and broadcasts messages.

Data Source: A service that streams or pushes new data to the Hub.

Client (Frontend): A web application (Blazor, React, or Angular) that listens to the Hub and updates the UI. 2. Setting Up the .NET SignalR Hub (Backend)

The backend is responsible for creating a Hub, which is a high-level pipeline that allows the client and server to call methods on each other. Step 1: Create a New Project

Create a new ASP.NET Core API or MVC project using .NET 9 or 10. Step 2: Implement the Hub

Create a class that inherits from Hub. This hub will handle connections and broadcast data to all clients.

using Microsoft.AspNetCore.SignalR; public class DashboardHub : Hub { // Optionally: Method for clients to send data to server public async Task SendMessage(string user, string message) { await Clients.All.SendAsync(“ReceiveMessage”, user, message); } } Use code with caution. Step 3: Register SignalR

Configure Program.cs to add SignalR services and map the hub endpoint.

var builder = WebApplication.CreateBuilder(args); // Add SignalR to services builder.Services.AddSignalR(); builder.Services.AddCors(); // Enable CORS for client connections var app = builder.Build(); // Map the Hub app.MapHub(“/dashboardhub”); app.MapCors(); app.Run(); Use code with caution. 3. Streaming Data to Clients

To make the dashboard live, you need to push data from the backend to the hub periodically. Creating a Background Service

Implement an IHostedService or BackgroundService to simulate data changes and call the hub.

public class DataStreamingService : BackgroundService { private readonly IHubContext _hubContext; public DataStreamingService(IHubContext hubContext) { _hubContext = hubContext; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { // Simulate generating new stock/metric data var data = new { Price = Random.Shared.Next(100, 1000), Time = DateTime.Now }; // Broadcast to all connected clients await _hubContext.Clients.All.SendAsync(“ReceiveData”, data); // Send updates every second await Task.Delay(1000, stoppingToken); } } } Use code with caution.

Register this service in Program.cs: builder.Services.AddHostedService();. 4. Connecting the Frontend (Client)

You can use the JavaScript SignalR client or the Blazor client to receive these updates. JavaScript Client Example javascript

const connection = new signalR.HubConnectionBuilder() .withUrl(“/dashboardhub”) .build(); connection.on(“ReceiveData”, (data) => { console.log(data); document.getElementById(“price”).innerText = data.price; // Update chart logic here }); connection.start().catch(err => console.error(err)); Use code with caution. Blazor Component Example

@page “/” @inject NavigationManager Navigation @using Microsoft.AspNetCore.SignalR.Client @implements IAsyncDisposable

Current Data: @currentData

@code { private HubConnection? hubConnection; private string? currentData; protected override async Task OnInitializedAsync() { hubConnection = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri(“/dashboardhub”)) .Build(); hubConnection.On(“ReceiveData”, (data) => { currentData = data; StateHasChanged(); // Re-render component }); await hubConnection.StartAsync(); } public async ValueTask DisposeAsync() { if (hubConnection is not null) { await hubConnection.DisposeAsync(); } } } Use code with caution. 5. Scaling and Production

For high-load scenarios (many concurrent users), you can use the Azure SignalR Service. It handles scaling and connection management, allowing your app to scale to millions of connections without manual infrastructure management.

Building live dashboards with SignalR and .NET is efficient, leveraging WebSockets for instant, bi-directional communication. By following these steps, you can create a robust, real-time data experience that improves user engagement and operational awareness. If you are interested in exploring further, I can help you: Secure your SignalR Hubs with authorization.

Integrate charting libraries like Chart.js or Blazor-ApexCharts. Scale the application using Redis backplane.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

More posts