Build a real-time monitoring dashboard that updates instantly without page refreshes using SignalR and ASP.NET Core.
Step 1: Setup SignalR in ASP.NET Core
# Create SignalR project dotnet new webapi -n RealTimeDashboard cd RealTimeDashboard # Add SignalR package dotnet add package Microsoft.AspNetCore.SignalR
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
policy => policy
.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
// Add SignalR
builder.Services.AddSignalR();
// Add background service for data generation
builder.Services.AddHostedService<DataGeneratorService>();
var app = builder.Build();
app.UseCors("CorsPolicy");
app.UseRouting();
// Map SignalR hub
app.MapHub<DashboardHub>("/dashboardHub");
app.Run();
Step 2: Create SignalR Hub
// Hubs/DashboardHub.cs
public class DashboardHub : Hub
{
private readonly ILogger<DashboardHub> _logger;
private static int _connectionCount = 0;
public DashboardHub(ILogger<DashboardHub> logger)
{
_logger = logger;
}
public override async Task OnConnectedAsync()
{
Interlocked.Increment(ref _connectionCount);
_logger.LogInformation("Client connected. Total connections: {Count}", _connectionCount);
await Clients.All.SendAsync("ConnectionCount", _connectionCount);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
Interlocked.Decrement(ref _connectionCount);
_logger.LogInformation("Client disconnected. Total connections: {Count}", _connectionCount);
await Clients.All.SendAsync("ConnectionCount", _connectionCount);
await base.OnDisconnectedAsync(exception);
}
// Method called by clients
public async Task SubscribeToMetric(string metricName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, metricName);
_logger.LogInformation("Client {ConnectionId} subscribed to {Metric}",
Context.ConnectionId, metricName);
}
public async Task UnsubscribeFromMetric(string metricName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, metricName);
_logger.LogInformation("Client {ConnectionId} unsubscribed from {Metric}",
Context.ConnectionId, metricName);
}
// Send data to specific client
public async Task SendPrivateMessage(string userId, string message)
{
await Clients.User(userId).SendAsync("ReceiveMessage", message);
}
}
Step 3: Background Data Generator
// Services/DataGeneratorService.cs
public class DataGeneratorService : BackgroundService
{
private readonly IHubContext<DashboardHub> _hubContext;
private readonly ILogger<DataGeneratorService> _logger;
private readonly Random _random = new();
public DataGeneratorService(IHubContext<DashboardHub> hubContext, ILogger<DataGeneratorService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Data generator started");
var metrics = new[]
{
"cpu", "memory", "requests", "errors", "responseTime"
};
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Generate random data for each metric
foreach (var metric in metrics)
{
var value = GenerateMetricValue(metric);
await _hubContext.Clients.Group(metric).SendAsync("MetricUpdate", new
{
Metric = metric,
Value = value,
Timestamp = DateTime.UtcNow
});
}
// Send to all clients
await _hubContext.Clients.All.SendAsync("Heartbeat", DateTime.UtcNow);
// Generate random alerts
if (_random.NextDouble() < 0.1) // 10% chance
{
await _hubContext.Clients.All.SendAsync("Alert", new
{
Level = _random.Next(1, 4) switch
{
1 => "Info",
2 => "Warning",
3 => "Error",
_ => "Info"
},
Message = $"Random alert at {DateTime.UtcNow:HH:mm:ss}",
Timestamp = DateTime.UtcNow
});
}
await Task.Delay(1000, stoppingToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating data");
await Task.Delay(5000, stoppingToken);
}
}
}
private double GenerateMetricValue(string metric)
{
return metric switch
{
"cpu" => _random.NextDouble() * 100,
"memory" => 100 + _random.NextDouble() * 900,
"requests" => _random.Next(50, 500),
"errors" => _random.Next(0, 10),
"responseTime" => _random.Next(10, 200),
_ => _random.NextDouble() * 100
};
}
}
Step 4: React SignalR Client
// src/hubs/dashboardHub.ts
import * as signalR from '@microsoft/signalr';
class DashboardHubService {
private connection: signalR.HubConnection | null = null;
private subscribers: Map<string, Function[]> = new Map();
constructor() {
this.connection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:5000/dashboardHub')
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Information)
.build();
}
async start() {
if (!this.connection) return;
try {
await this.connection.start();
console.log('SignalR connected');
// Set up event handlers
this.connection.on('MetricUpdate', (data) => {
this.emit('metricUpdate', data);
});
this.connection.on('Alert', (data) => {
this.emit('alert', data);
});
this.connection.on('ConnectionCount', (count) => {
this.emit('connectionCount', count);
});
this.connection.on('Heartbeat', (timestamp) => {
this.emit('heartbeat', timestamp);
});
} catch (err) {
console.error('SignalR connection failed:', err);
}
}
async subscribeToMetric(metric: string) {
if (!this.connection) return;
await this.connection.invoke('SubscribeToMetric', metric);
}
async unsubscribeFromMetric(metric: string) {
if (!this.connection) return;
await this.connection.invoke('UnsubscribeFromMetric', metric);
}
on(event: string, callback: Function) {
if (!this.subscribers.has(event)) {
this.subscribers.set(event, []);
}
this.subscribers.get(event)?.push(callback);
}
private emit(event: string, data: any) {
const callbacks = this.subscribers.get(event) || [];
callbacks.forEach(callback => callback(data));
}
async stop() {
if (!this.connection) return;
await this.connection.stop();
}
}
export default new DashboardHubService();
Step 5: React Dashboard Component
// src/components/Dashboard.tsx
import React, { useState, useEffect } from 'react';
import { Card, Grid, Typography, Paper, Box } from '@mui/material';
import { Line } from 'react-chartjs-2';
import dashboardHub from '../hubs/dashboardHub';
interface MetricData {
metric: string;
value: number;
timestamp: string;
}
interface AlertData {
level: string;
message: string;
timestamp: string;
}
const Dashboard: React.FC = () => {
const [metrics, setMetrics] = useState<Record<string, number>>({});
const [alerts, setAlerts] = useState<AlertData[]>([]);
const [connectionCount, setConnectionCount] = useState(0);
const [history, setHistory] = useState<MetricData[]>([]);
useEffect(() => {
// Start SignalR connection
dashboardHub.start();
// Subscribe to metrics
dashboardHub.subscribeToMetric('cpu');
dashboardHub.subscribeToMetric('memory');
dashboardHub.subscribeToMetric('requests');
// Event handlers
const handleMetricUpdate = (data: MetricData) => {
setMetrics(prev => ({
...prev,
[data.metric]: data.value
}));
setHistory(prev => [...prev.slice(-50), data]);
};
const handleAlert = (data: AlertData) => {
setAlerts(prev => [data, ...prev].slice(0, 10));
// Show notification
if (data.level === 'Error') {
console.error('Alert:', data.message);
}
};
const handleConnectionCount = (count: number) => {
setConnectionCount(count);
};
// Register event listeners
dashboardHub.on('metricUpdate', handleMetricUpdate);
dashboardHub.on('alert', handleAlert);
dashboardHub.on('connectionCount', handleConnectionCount);
// Cleanup
return () => {
dashboardHub.stop();
};
}, []);
// Chart data
const chartData = {
labels: history.map(d => new Date(d.timestamp).toLocaleTimeString()),
datasets: [
{
label: 'CPU (%)',
data: history.filter(d => d.metric === 'cpu').map(d => d.value),
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
},
{
label: 'Memory (MB)',
data: history.filter(d => d.metric === 'memory').map(d => d.value),
borderColor: 'rgb(255, 99, 132)',
tension: 0.1
},
{
label: 'Requests',
data: history.filter(d => d.metric === 'requests').map(d => d.value),
borderColor: 'rgb(54, 162, 235)',
tension: 0.1
}
]
};
return (
{/* Header */}
Live Dashboard
Connected Clients: {connectionCount}
{/* Metric Cards */}
{Object.entries(metrics).map(([key, value]) => (
{key.toUpperCase()}
{value.toFixed(1)}
{key === 'cpu' && '%'}
{key === 'memory' && ' MB'}
))}
{/* Chart */}
{/* Alerts */}
Recent Alerts
{alerts.map((alert, index) => (
[{alert.level}] {alert.message} - {new Date(alert.timestamp).toLocaleTimeString()}
))}
);
};
export default Dashboard;
Step 6: Run the Application
# Start backend
cd RealTimeDashboard
dotnet run
# Start frontend (React)
cd client
npm install
npm start
# Open browser: http://localhost:3000
# Test with multiple tabs
# Open multiple browser windows
# Watch real-time updates across all tabs!
# Scale horizontally
# SignalR supports Redis backplane for scaling
dotnet add package Microsoft.AspNetCore.SignalR.StackExchangeRedis
builder.Services.AddSignalR()
.AddStackExchangeRedis(options =>
{
options.Configuration = "localhost:6379";
});
# Now multiple instances share state