Sending Notifications to Web and Mobile Users Using .NET Core and React
Notify your users with web and mobile
Notifications are a powerful tool for keeping users engaged and informed about important updates in your application. Whether it’s sending real-time alerts or transactional messages, adding a notification system to your web and mobile applications can significantly enhance the user experience.
In this blog, we’ll focus on how to send notifications to both web and mobile users using .NET Core as the backend and React for the frontend. We’ll explore setting up a notification service, handling web notifications, and triggering notifications for mobile users using third-party services like Firebase.
Key Components of the Notification System
Backend in .NET Core: To handle sending notifications to users.
Frontend in React: To display real-time notifications on the web.
Firebase Cloud Messaging (FCM): For mobile push notifications.
1. Setting Up the Notification Service in .NET Core
We’ll start by creating a Notification Service in .NET Core. This service will be responsible for sending notifications to both web and mobile clients.
Step 1: Create a Notification Model
Define a model that represents a notification in your application.
public class Notification
{
public string Title { get; set; }
public string Message { get; set; }
public string UserId { get; set; } // Identify the user to send the notification to
public bool IsMobile { get; set; } // Whether it's a mobile notification
public DateTime CreatedAt { get; set; }
}
Step 2: Create the Notification Service
In the service layer, implement logic to send notifications to users. This can include sending notifications to both web clients (via SignalR) and mobile clients (via Firebase Cloud Messaging).
SignalR for Web Notifications
SignalR is a library that enables real-time web functionality, allowing the server to push notifications to connected web clients.
First, install the SignalR NuGet package:
dotnet add package Microsoft.AspNetCore.SignalR
Next, set up a Hub that will handle notification broadcasting.
using Microsoft.AspNetCore.SignalR;
public class NotificationHub : Hub
{
public async Task SendNotification(string userId, string title, string message)
{
// Send a notification to the specific user
await Clients.User(userId).SendAsync("ReceiveNotification", title, message);
}
}
Firebase Cloud Messaging (FCM) for Mobile Notifications
For mobile devices, we can use Firebase Cloud Messaging (FCM) to send push notifications.
Install the FirebaseAdmin NuGet package to integrate Firebase with .NET Core:
dotnet add package FirebaseAdmin
Set up Firebase service:
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
public class FirebaseService
{
private FirebaseApp _firebaseApp;
public FirebaseService()
{
_firebaseApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/firebase-adminsdk.json")
});
}
public async Task SendMobileNotification(string userToken, string title, string message)
{
var notification = new Message()
{
Token = userToken,
Notification = new Notification
{
Title = title,
Body = message
}
};
await FirebaseMessaging.DefaultInstance.SendAsync(notification);
}
}
Step 3: Combine Web and Mobile Notification Logic
Now, let’s combine both SignalR for web notifications and Firebase for mobile notifications into a single service.
public class NotificationService
{
private readonly IHubContext<NotificationHub> _hubContext;
private readonly FirebaseService _firebaseService;
public NotificationService(IHubContext<NotificationHub> hubContext, FirebaseService firebaseService)
{
_hubContext = hubContext;
_firebaseService = firebaseService;
}
public async Task SendNotification(Notification notification)
{
if (notification.IsMobile)
{
// Send notification to mobile using Firebase
await _firebaseService.SendMobileNotification(notification.UserId, notification.Title, notification.Message);
}
else
{
// Send notification to web using SignalR
await _hubContext.Clients.User(notification.UserId).SendAsync("ReceiveNotification", notification.Title, notification.Message);
}
}
}
This service allows you to send notifications to both web and mobile users based on whether the IsMobile
flag is set.
2. Setting Up the React Frontend for Web Notifications
On the frontend side, you’ll use React to display real-time notifications to users via SignalR.
Step 1: Install SignalR Client
Install the SignalR client package in your React project:
npm install @microsoft/signalr
Step 2: Connect to the SignalR Hub in React
Create a connection to the SignalR Notification Hub on the server.
import React, { useEffect, useState } from 'react';
import * as signalR from '@microsoft/signalr';
function NotificationComponent() {
const [notifications, setNotifications] = useState([]);
useEffect(() => {
const connection = new signalR.HubConnectionBuilder()
.withUrl("/notificationHub")
.build();
connection.start()
.then(() => console.log('SignalR Connected'))
.catch(err => console.error('Error connecting SignalR:', err));
connection.on("ReceiveNotification", (title, message) => {
setNotifications(prevNotifications => [...prevNotifications, { title, message }]);
});
return () => {
connection.stop();
};
}, []);
return (
<div>
<h3>Notifications</h3>
<ul>
{notifications.map((n, index) => (
<li key={index}><strong>{n.title}:</strong> {n.message}</li>
))}
</ul>
</div>
);
}
export default NotificationComponent;
In this example, when the server pushes a notification using SignalR, the React app listens for the ReceiveNotification
event and displays the notification in the UI.
3. Sending Mobile Push Notifications Using Firebase
For mobile apps, you will need to integrate Firebase Cloud Messaging (FCM) into the mobile frontend (whether it’s a React Native app or native Android/iOS apps).
Step 1: Set Up Firebase in Mobile App
Follow Firebase’s official guides to set up FCM in your mobile application:
Firebase for Android
Firebase for iOS
Step 2: Obtain the FCM Token
In your mobile app, obtain the FCM token for each user, which you will use to target them when sending notifications.
Step 3: Use .NET Core Backend to Send Push Notifications
When you call the NotificationService
on the backend with IsMobile
set to true, it will use Firebase to send push notifications to the mobile app, ensuring that mobile users receive updates in real-time.
Conclusion
This blog demonstrates how to send notifications to both web users and mobile users using .NET Core and React:
For web notifications, we used SignalR to push notifications in real-time to connected web clients.
For mobile notifications, we leveraged Firebase Cloud Messaging (FCM) to send push notifications.
By implementing this approach, you can ensure that your users, whether on a web browser or a mobile device, stay up-to-date with important events in your application in real time.