.NET Real-Time Notifications with Firebase Cloud Messaging (FCM)

Real-Time Notifications in .NET with Firebase Cloud Messaging (FCM)

In today’s fast-paced digital world, real-time notifications play a crucial role in enhancing user engagement. Whether it’s a new message, order update, or breaking news alert, timely notifications keep users informed.

For .NET developers, Firebase Cloud Messaging (FCM) is an excellent choice for implementing real-time notifications in web and mobile applications. In this guide, we’ll explore how to integrate FCM with a .NET application to send and receive push notifications efficiently.


What is Firebase Cloud Messaging (FCM)?

Firebase Cloud Messaging (FCM) is a free, cross-platform messaging solution by Google that allows you to send messages and notifications reliably. It supports:

Android, iOS, and Web Apps
Topic-based and User-specific notifications
High-priority and silent background messages
Integration with Firebase Analytics and Crashlytics


Setting Up Firebase for .NET

To integrate Firebase Cloud Messaging (FCM) with a .NET application, follow these steps:

Step 1: Create a Firebase Project

  1. Visit the Firebase Console and sign in with a Google account.
  2. Click Add Project and enter a project name.
  3. Enable Google Analytics (optional) and complete the setup.

Step 2: Get Firebase Server Key

  1. In the Firebase console, go to Project Settings → Cloud Messaging.
  2. Locate the Server Key (Legacy Key) – This key will be used in our .NET application to send notifications.

Step 3: Register Your App

  1. In Firebase Console, navigate to Project Settings → General.
  2. Click Add App and select your platform (Android, iOS, or Web).
  3. Follow the steps to register the app and download the google-services.json or firebase-config.js file (for web).

Building a .NET Backend for FCM

Now, let’s set up a .NET 7 Web API to send push notifications using FCM.

Step 1: Install Required NuGet Packages

Open the .NET project and install the Google.Apis.FirebaseCloudMessaging.v1 package:

dotnet add package Google.Apis.FirebaseCloudMessaging.v1

Alternatively, install it using the Package Manager Console:

Install-Package Google.Apis.FirebaseCloudMessaging.v1

Step 2: Create a Firebase Messaging Service

Create a new service class FirebaseNotificationService.cs:

using Google.Apis.Auth.OAuth2;
using Google.Apis.FirebaseCloudMessaging.v1;
using Google.Apis.FirebaseCloudMessaging.v1.Data;
using Google.Apis.Services;
using System.Threading.Tasks;

public class FirebaseNotificationService
{
    private readonly FirebaseCloudMessagingService _fcmService;

    public FirebaseNotificationService()
    {
        GoogleCredential credential = GoogleCredential.FromFile("firebase-service-account.json")
            .CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
        
        _fcmService = new FirebaseCloudMessagingService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
        });
    }

    public async Task SendNotification(string deviceToken, string title, string message)
    {
        var request = new SendMessageRequest
        {
            Message = new Message
            {
                Token = deviceToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = message
                }
            }
        };

        await _fcmService.Projects.Messages.Send(request, "projects/YOUR-PROJECT-ID").ExecuteAsync();
    }
}

Key Highlights:

  • Uses Firebase Service Account Key for authentication.
  • Sends a notification to a specific device token.

Sending Push Notifications from a Controller

Now, let's create an API endpoint to trigger notifications.

Step 1: Add Firebase Service in Dependency Injection

Modify Program.cs to register the service:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<FirebaseNotificationService>();

var app = builder.Build();
app.MapControllers();
app.Run();

Step 2: Create an API Controller

Create a new controller NotificationController.cs:

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

[Route("api/notifications")]
[ApiController]
public class NotificationController : ControllerBase
{
    private readonly FirebaseNotificationService _notificationService;

    public NotificationController(FirebaseNotificationService notificationService)
    {
        _notificationService = notificationService;
    }

    [HttpPost("send")]
    public async Task<IActionResult> SendNotification([FromBody] NotificationRequest request)
    {
        await _notificationService.SendNotification(request.DeviceToken, request.Title, request.Message);
        return Ok(new { Status = "Notification Sent" });
    }
}

public class NotificationRequest
{
    public string DeviceToken { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
}

Now, you can send notifications using:

POST /api/notifications/send
{
  "deviceToken": "FCM_DEVICE_TOKEN",
  "title": "New Update!",
  "message": "Check out the latest features."
}

Receiving Notifications in a .NET Web App

If you are building a Blazor or MVC app, you can integrate Firebase JavaScript SDK to listen for notifications.

Step 1: Install Firebase in Frontend

For JavaScript-based apps, add Firebase SDK:

<script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js"></script>

Step 2: Initialize Firebase Messaging

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onMessage((payload) => {
  console.log("Message received: ", payload);
});

Your app can now receive push notifications in real-time!


Best Practices for FCM in .NET

🔹 Use Topic-Based Messaging: Subscribe users to topics (news-updates, order-status).
🔹 Handle Notification Click Events: Redirect users based on the type of notification.
🔹 Use Silent Push Notifications: Send background updates without alerting the user.
🔹 Optimize for Battery Life: Avoid frequent push notifications to reduce battery drain.


Conclusion

Firebase Cloud Messaging (FCM) is a powerful tool for sending real-time notifications in .NET applications. Whether you are working on mobile, web, or desktop apps, integrating FCM can greatly enhance user engagement. By following this guide, you can set up FCM, send notifications, and receive messages seamlessly in a .NET environment.

👉 Next Steps?

  • Explore Topic-Based Messaging for mass notifications.
  • Implement Push Subscription Management for users.
  • Enhance security using OAuth and API Key Restrictions.

💬 What are your thoughts on FCM integration in .NET? Let’s discuss in the comments! 🚀


FAQs

1. Is Firebase Cloud Messaging (FCM) free?

Yes, FCM is free and allows unlimited push notifications across platforms.

2. Can I send notifications to multiple users?

Yes, you can send messages to multiple devices using topics or device groups.

3. Does FCM support iOS notifications?

Yes, FCM works for iOS but requires additional setup using Apple Push Notification Service (APNs).

4. How do I debug push notifications in .NET?

Use Firebase Diagnostics Tool and check FCM logs for troubleshooting.

5. Can I use FCM with Blazor WebAssembly?

Yes, FCM can be integrated into Blazor WebAssembly using JavaScript Interop.

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