Building Real-Time Notification System with .NET Core and SignalR

Building Real-Time Notification System with .NET Core and SignalR

In this blog post, we'll create a real-time notification system for a web application using SignalR and .NET Core. We'll cover both backend and frontend integration to make notifications interactive and dynamic.

Introduction

Real-time notifications have become a key feature in modern web applications. They provide users with immediate feedback or updates, which are crucial for enhancing user engagement and improving application functionality. For instance, when new messages arrive, a task is completed, or an event occurs, real-time notifications immediately inform the user. SignalR, an open-source library for ASP.NET, makes it easy to add this real-time functionality to your applications.

In this tutorial, we will create a simple real-time notification system that pushes updates from the server to the client as soon as an event occurs. We will use SignalR with .NET Core for the backend and Angular for the frontend. SignalR allows for persistent connections and enables immediate communication with clients through WebSockets or other transport mechanisms.

Prerequisites

Before we begin, ensure you have the following:

  • Visual Studio or any C# IDE that supports .NET Core development.
  • Node.js and npm installed for Angular development.
  • Basic understanding of ASP.NET Core, SignalR, and JavaScript.
  • Familiarity with Angular framework to implement the frontend part.

If you're new to SignalR or Angular, don't worry. We will explain each step clearly and provide implementation examples throughout this post.

The following diagram illustrates Real-Time Notification System with .NET Core and SignalR:

secure authentication with JWT and Identityserver

Backend Setup - SignalR in .NET Core

The first step is to configure SignalR in the backend. We'll begin by installing the SignalR NuGet package, then create the SignalR Hub, and finally configure it in our ASP.NET Core application.

Step 1: Install SignalR NuGet Package

SignalR is available as a NuGet package, so we need to install it in our project. Open the NuGet package manager or use the .NET CLI to install the package:

Install-Package Microsoft.AspNetCore.SignalR

Step 2: Create SignalR Hub

A SignalR Hub is a server-side class that handles incoming connections from clients and allows the server to broadcast messages to clients. Let's create a simple Hub class:

using Microsoft.AspNetCore.SignalR;

public class NotificationHub : Hub
{
    // Sends a notification to all connected clients
    public async Task SendNotification(string message)
    {
        await Clients.All.SendAsync("ReceiveNotification", message);
    }
}
            

The SendNotification method sends messages to all clients that are connected to the Hub. The ReceiveNotification method is the event handler that clients will use to receive the message.

Step 3: Configure SignalR in Startup.cs

Now, we need to configure SignalR in the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR(); // Register SignalR services
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<NotificationHub>("/notificationHub");
    });
}
            

In the ConfigureServices method, we add the SignalR service to the application's service container. In the Configure method, we map the SignalR hub to a specific route.

Frontend Setup - Angular Integration

Now that we have our SignalR backend set up, let's move on to integrating SignalR with the frontend using Angular. We'll install the SignalR client, set up a service to handle the connection, and display notifications in the user interface.

Step 1: Install SignalR JavaScript Client

We need to install the SignalR client for JavaScript. Use npm to install the package:

npm install @microsoft/signalr

Step 2: Create SignalR Service in Angular

Create a service to manage the connection between the client and the SignalR hub:

import { Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  private hubConnection: HubConnection;

  constructor() {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl("https://localhost:5001/notificationHub")
      .build();

    // Listen for notifications
    this.hubConnection.on("ReceiveNotification", (message) => {
      alert(message); // Show the notification in an alert box
    });

    this.hubConnection.start().catch(err => console.error("SignalR connection failed: ", err));
  }

  // Method to send notifications
  sendNotification(message: string) {
    this.hubConnection.invoke("SendNotification", message)
      .catch(err => console.error("Sending notification failed: ", err));
  }
}
            

The NotificationService service establishes a connection with the SignalR Hub and listens for notifications. The sendNotification method sends a notification to the server.

Step 3: Display Notifications in the Angular Component

Now, in the Angular component, we'll inject the NotificationService and trigger notifications from the UI. Here's an example of how to display notifications when the user clicks a button:

import { Component } from '@angular/core';
import { NotificationService } from './notification.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private notificationService: NotificationService) {}

  sendNotification() {
    this.notificationService.sendNotification("Hello, this is a test notification!");
  }
}
            

When the user clicks the button, the message will be sent to all connected clients in real time.

Handling Different Notification Types

You can extend your notification system to handle different notification types. For instance, you might want to categorize notifications as "warning", "info", or "error". You can define a Notification class that contains these types and more information.

public class Notification
{
    public string Type { get; set; }
    public string Message { get; set; }
    public DateTime Timestamp { get; set; }
}
            

Then, modify the SendNotification method to send a Notification object:

public async Task SendNotification(Notification notification)
{
    await Clients.All.SendAsync("ReceiveNotification", notification);
}
            

In the frontend, modify the service to handle the structured notification and display it accordingly.

Advanced Features for Real-Time Notifications

Once you have the basic notification system in place, you can enhance it with the following advanced features:

  • Private Notifications - Send notifications to specific users by managing connections and groups in SignalR.
  • Push Notifications - Integrate browser push notifications using libraries like web-push to send notifications even when the user is not actively using the app.
  • Notification Queue - For handling high traffic and improving performance, you can manage a queue of notifications before broadcasting them to clients.

These features can be used to further personalize and optimize your notification system based on user preferences and application needs.

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post