React + .
NET Core Notifications System
Scenario
- After a user logs in or registers, on the dashboard header, a notification icon fetches and shows
project-related notifications.
Backend (ASP.NET Core)
1. Create Notification Model
public class Notification
public int Id { get; set; }
public int UserId { get; set; }
public string Message { get; set; }
public bool IsRead { get; set; } = false;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
2. Create NotificationsController
[ApiController]
[Route("api/[controller]")]
public class NotificationsController : ControllerBase
private readonly YourDbContext _context;
public NotificationsController(YourDbContext context)
{
_context = context;
[HttpGet("user/{userId}")]
public async Task<IActionResult> GetUserNotifications(int userId)
var notifications = await _context.Notifications
.Where(n => n.UserId == userId)
.OrderByDescending(n => n.CreatedAt)
.ToListAsync();
return Ok(notifications);
3. Insert Notification on Registration/Login
_context.Notifications.Add(new Notification
UserId = user.Id,
Message = "Welcome! Your registration was successful."
});
await _context.SaveChangesAsync();
Frontend (React)
1. Install Axios
npm install axios
2. Fetch Notifications in Header Component
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function NotificationIcon({ userId }) {
const [notifications, setNotifications] = useState([]);
useEffect(() => {
axios.get(`/api/notifications/user/${userId}`)
.then(response => setNotifications(response.data))
.catch(error => console.error(error));
}, [userId]);
return (
<div>
<span>Notification</span>
<span>{notifications.length}</span>
<div className="dropdown">
{notifications.map((n, index) => (
<div key={index}>
{n.message}
<small>{new Date(n.createdAt).toLocaleString()}</small>
</div>
))}
</div>
</div>
);
export default NotificationIcon;
3. Use in Dashboard Header
<NotificationIcon userId={loggedInUserId} />
Easy Tips
- Use SignalR for real-time notifications later.
- Limit number of fetched notifications for performance.
- Add an "isRead" toggle when panel opens.
Summary
Feature | Implementation
------------------|--------------------------
Notification model | Created in backend
API endpoint | /api/notifications/user/{id}
React header icon | Fetches via Axios
Notification logic | On register/login/server events