SignalR  

Real-Time Applications with SignalR, Angular, and ASP.NET Core

Introduction

Real-time applications are apps that update instantly without needing to refresh the page. Examples include chat apps, live dashboards, notifications, and online games.

With ASP.NET Core and SignalR, we can push updates from the server to clients in real-time. Angular helps us create a responsive frontend to display this data instantly.

In this tutorial, we will build a simple real-time chat application using ASP.NET Core and Angular.

Architecture Diagram

Here’s a high-level workflow of our real-time app:

+----------------+          WebSocket / SignalR          +----------------+
|   Angular App  | <---------------------------------->  | ASP.NET Core   |
|   (Frontend)   |                                      |  Server       |
+----------------+                                      +----------------+
        ^                                                      |
        |                                                      |
        +------------------ Database (SQL Server) ------------+

Explanation:

  • Angular connects to ASP.NET Core via SignalR Hub.

  • Messages from one client are sent to the server.

  • Server pushes the message to all connected clients instantly.

  • Optionally, messages are stored in a SQL Server database for persistence.

Step 1. Create ASP.NET Core Backend

  1. Create a new ASP.NET Core Web API project:

dotnet new webapi -n RealTimeChatApp
cd RealTimeChatApp
  1. Add SignalR NuGet package:

dotnet add package Microsoft.AspNetCore.SignalR
  1. Create a Hub Class:

using Microsoft.AspNetCore.SignalR;

namespace RealTimeChatApp.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}
  1. Configure SignalR in Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSignalR();
var app = builder.Build();
app.MapControllers();
app.MapHub<ChatHub>("/chathub");
app.Run();

Step 2. Create Angular Frontend

  1. Create a new Angular project:

ng new real-time-chat --routing=false --style=css
cd real-time-chat
  1. Install SignalR client:

npm install @microsoft/signalr
  1. Create a Chat Service (chat.service.ts):

import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ChatService {
  private hubConnection!: signalR.HubConnection;
  public messages = new BehaviorSubject<{user:string, message:string}[]>([]);

  public startConnection() {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:5001/chathub')
      .build();

    this.hubConnection.start().then(() => console.log('SignalR Connected'));

    this.hubConnection.on('ReceiveMessage', (user, message) => {
      const currentMessages = this.messages.value;
      currentMessages.push({ user, message });
      this.messages.next(currentMessages);
    });
  }

  public sendMessage(user: string, message: string) {
    this.hubConnection.invoke('SendMessage', user, message)
      .catch(err => console.error(err));
  }
}
  1. Update app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ChatService } from './chat.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  user = '';
  message = '';

  constructor(public chatService: ChatService) {}

  ngOnInit() {
    this.chatService.startConnection();
  }

  sendMessage() {
    if(this.user && this.message) {
      this.chatService.sendMessage(this.user, this.message);
      this.message = '';
    }
  }
}
  1. Update app.component.html:

<div>
  <h2>Real-Time Chat App</h2>
  <input type="text" placeholder="Your name" [(ngModel)]="user" />
  <input type="text" placeholder="Message" [(ngModel)]="message" />
  <button (click)="sendMessage()">Send</button>

  <div *ngFor="let msg of chatService.messages | async">
    <b>{{msg.user}}:</b> {{msg.message}}
  </div>
</div>

Step 3. Run the Application

  1. Run ASP.NET Core backend:

dotnet run
  1. Run Angular frontend:

ng serve
  1. Test: Open multiple browser tabs and send messages. All connected clients should see messages instantly.

Key Features

  • Real-time updates using SignalR.

  • Works with multiple clients.

  • Can be extended for notifications, dashboards, or collaborative apps.

  • Optional persistence in SQL Server.

Conclusion

Using SignalR with ASP.NET Core and Angular, you can create modern real-time web applications easily. This approach is scalable, efficient, and improves user experience.