Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Implementing Firebase Cloud Messaging (FCM) Push Notifications in ASP.NET Core

Implementing Firebase Cloud Messaging (FCM) Push Notifications in ASP.NET Core

Date- Apr 19,2026 71
firebase cloud

Overview

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that allows developers to send notifications and data messages to clients. It exists primarily to facilitate communication between server applications and clients, enabling the delivery of notifications directly to users, whether they are using web, Android, or iOS applications. The problem FCM solves is the need for a streamlined, reliable method to send messages to users, which can significantly improve user engagement and retention.

Real-world use cases for FCM include sending promotional notifications to users of a mobile application, alerting users of new messages or updates in a web application, and triggering background data synchronization. FCM is especially useful in applications that require real-time updates, such as messaging apps, news applications, or social media platforms. By utilizing FCM, developers can ensure that their applications remain interactive and responsive to users' needs.

Prerequisites

  • ASP.NET Core: Familiarity with ASP.NET Core framework for building web applications.
  • Firebase Account: A Google Firebase account to access FCM services.
  • Node.js: Installed for using Firebase CLI to initialize the project.
  • Postman: Tool for testing API endpoints easily.
  • NuGet Packages: Understanding of how to manage NuGet packages in ASP.NET Core.

Setting Up Firebase Cloud Messaging

To begin using FCM, you must first set up a Firebase project. This involves creating a new project in the Firebase console, enabling FCM, and obtaining your server key and sender ID, which are essential for configuring your ASP.NET Core application to communicate with FCM.

After creating a Firebase project, navigate to the project settings and select the "Cloud Messaging" tab. Here, you will find your Server Key and Sender ID. The Server Key is crucial for authenticating your requests to FCM, while the Sender ID is used to identify your app when sending messages.

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddHttpClient(); // For making HTTP requests to FCM
}

The above code snippet shows how to configure an ASP.NET Core application to use the built-in dependency injection system to add the HttpClient service. This will allow us to make HTTP requests to the FCM API.

Creating the Notification Service

Next, we will create a service class that will handle the sending of notifications to FCM. This service will encapsulate all logic related to FCM interactions, allowing for a clean separation of concerns.

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class NotificationService
{
    private readonly HttpClient _httpClient;
    private readonly string _serverKey;

    public NotificationService(HttpClient httpClient, string serverKey)
    {
        _httpClient = httpClient;
        _serverKey = serverKey;
    }

    public async Task SendNotificationAsync(string deviceToken, string title, string body)
    {
        var messageInformation = new
        {
            to = deviceToken,
            notification = new
            {
                title,
                body
            }
        };

        var jsonMessage = JsonConvert.SerializeObject(messageInformation);
        var request = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send");
        request.Headers.Authorization = new AuthenticationHeaderValue("key", _serverKey);
        request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");

        var response = await _httpClient.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception("Failed to send notification: " + response.ReasonPhrase);
        }
    }
}

This NotificationService class is crucial for sending notifications. Here's a breakdown of its components:

  • HttpClient: Used for making HTTP requests to the FCM endpoint.
  • Server Key: Authenticates requests sent to FCM.
  • SendNotificationAsync: This method constructs the notification payload and sends it to the FCM endpoint using a POST request.

Integrating Notification Service into Controllers

Once the NotificationService is implemented, it can be injected into an ASP.NET Core controller where notifications can be triggered based on specific actions, such as user registration or message receipt.

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class NotificationsController : ControllerBase
{
    private readonly NotificationService _notificationService;

    public NotificationsController(NotificationService notificationService)
    {
        _notificationService = notificationService;
    }

    [HttpPost]
    [Route("send")] // Endpoint to send notification
    public async Task SendNotification([FromBody] NotificationRequest request)
    {
        await _notificationService.SendNotificationAsync(request.DeviceToken, request.Title, request.Body);
        return Ok();
    }
}

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

This controller defines an endpoint api/notifications/send that accepts a POST request with the notification details. The SendNotification method calls the SendNotificationAsync method of the NotificationService.

Testing the Notification Endpoint

To test the notification sending functionality, you can use Postman or any similar tool. Set the request type to POST, and the URL to http://localhost:5000/api/notifications/send. In the body, include a JSON object containing the device token, title, and body for the notification.

{
    "DeviceToken": "",
    "Title": "Test Notification",
    "Body": "This is a test notification."
}

Upon sending this request, if successful, you should receive a 200 OK response. The device with the specified token should receive the notification.

Edge Cases & Gotchas

When working with FCM, developers may encounter several edge cases and gotchas. One common pitfall is the handling of expired or invalid device tokens. If a notification is sent to an invalid token, FCM will return an error response.

if (response.StatusCode == HttpStatusCode.NotFound)
{
    // Handle the case where the token is invalid
}

The above code snippet demonstrates how to check for a NotFound status code in the response, indicating an invalid or expired device token. It's crucial to implement this check to prevent unnecessary API calls and to maintain a clean list of device tokens.

Performance & Best Practices

To optimize the performance of notifications sent via FCM, consider these best practices:

  • Batch Notifications: Instead of sending individual notifications, use FCM's ability to send notifications in batches. This reduces the number of requests and improves efficiency.
  • Use Topics: For applications with many users, consider using topics. Users can subscribe to topics, and you can send messages to all subscribers with a single request.
  • Prioritize Notifications: Set notification priorities based on urgency to ensure critical notifications reach users promptly.

Real-World Scenario: A Messaging Application

Let's consider a simple messaging application where users can send messages to each other. Whenever a message is sent, a push notification should be delivered to the recipient.

First, we will create a message model and a controller to handle message sending:

public class Message
{
    public string Sender { get; set; }
    public string Recipient { get; set; }
    public string Content { get; set; }
}

[ApiController]
[Route("api/[controller]")]
public class MessagesController : ControllerBase
{
    private readonly NotificationService _notificationService;

    public MessagesController(NotificationService notificationService)
    {
        _notificationService = notificationService;
    }

    [HttpPost]
    public async Task SendMessage([FromBody] Message message)
    {
        // Logic to save message in the database
        // Retrieve recipient's device token
        var deviceToken = GetDeviceTokenForUser(message.Recipient);

        // Send notification
        await _notificationService.SendNotificationAsync(deviceToken, "New Message", message.Content);
        return Ok();
    }
}

This MessagesController allows users to send messages, and upon sending, it triggers a notification to the recipient. The GetDeviceTokenForUser method should be implemented to retrieve the device token associated with the recipient's user account.

Conclusion

  • Firebase Cloud Messaging provides a robust solution for sending push notifications.
  • Proper setup and handling of notifications can significantly enhance user engagement in applications.
  • Best practices include batching notifications and using topics for better performance.
  • Handling edge cases such as invalid tokens is crucial for maintaining a reliable notification system.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Integrating AWS SQS and SNS in ASP.NET Core for Decoupled Microservices
May 10, 2026
Integrating Azure Service Bus with ASP.NET Core: Deep Dive into Queues, Topics, and Subscriptions
May 10, 2026
Integrating RabbitMQ with ASP.NET Core Using MassTransit: A Complete Guide
May 10, 2026
Integrating Hugging Face Inference API with ASP.NET Core for NLP Models
May 06, 2026
Previous in ASP.NET Core
Integrating SMTP2GO in ASP.NET Core for Reliable Email Delivery
Next in ASP.NET Core
Understanding and Resolving 'Service Not Registered' Errors in AS…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 366 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26191 views
  • Exception Handling Asp.Net Core 20938 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20391 views
  • How to implement Paypal in Asp.Net Core 19753 views
  • Task Scheduler in Asp.Net core 17705 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor