Push notifications are a critical part of modern apps โ they keep users informed and engaged in real-time.
In this article, weโll learn how to send push notifications from a .NET Core Web API using the Firebase Cloud Messaging (FCM) v1 API โ the latest and most secure way to communicate with client apps.
๐ง What is Firebase Cloud Messaging (FCM)?
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you send notifications and data messages reliably to Android, iOS, and web clients.
With the v1 HTTP API, Google moved from legacy key-based authentication to OAuth2-based authentication using service accounts, providing better security and scalability.
๐ Official Documentation:
Firebase Cloud Messaging HTTP v1 API (Google)
๐ฏ Why Use the v1 API?
| Feature | Legacy API | v1 API |
|---|
| Authentication | Server Key | OAuth2 (Service Account) |
| Message Format | JSON (limited) | Structured JSON (with advanced options) |
| Targeting | Tokens / Topics | Tokens / Topics / Conditions |
| Platform Support | Basic | Full (Android, iOS, Web) |
| Future Support | Deprecated | โ
Active |
๐งฑ Step-by-Step Implementation in .NET Core
Letโs implement a .NET Core Web API that can send notifications using Firebase Cloud Messaging v1 API.
โ๏ธ Step 1. Create a .NET Core Web API Project
dotnet new webapi -n FirebasePushAPI
cd FirebasePushAPI
๐ฆ Step 2. Install Required NuGet Packages
Install packages for Google Auth and HTTP communication:
dotnet add package Google.Apis.Auth
dotnet add package Newtonsoft.Json
๐ Step 3. Create a Firebase Service Account Key
Go to Firebase Console.
Navigate to Project Settings โ Service Accounts โ Generate new private key.
Download the JSON file and save it securely (e.g., /App_Data/firebase-key.json).
โ ๏ธ Never commit this file to source control.
๐งฉ Step 4. Create a Model for Notification Request
namespace FirebasePushAPI.Models
{
public class FcmNotificationRequest
{
public string Token { get; set; } // FCM device token
public string Title { get; set; }
public string Body { get; set; }
public string ImageUrl { get; set; }
}
}
๐ช Step 5. Create a Firebase Notification Service
Create a new file Services/FirebaseService.cs:
using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;
using System.Net.Http.Headers;
namespace FirebasePushAPI.Services
{
public class FirebaseService
{
private readonly string _projectId = "your-firebase-project-id";
private readonly string _firebaseKeyPath = "App_Data/firebase-key.json";
public async Task<bool> SendNotificationAsync(string token, string title, string body, string imageUrl = null)
{
var message = new
{
message = new
{
token = token,
notification = new
{
title = title,
body = body,
image = imageUrl
}
}
};
var accessToken = await GetAccessTokenAsync();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
var json = JsonConvert.SerializeObject(message);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(
$"https://fcm.googleapis.com/v1/projects/{_projectId}/messages:send",
content);
return response.IsSuccessStatusCode;
}
}
private async Task<string> GetAccessTokenAsync()
{
GoogleCredential credential;
using (var stream = new FileStream(_firebaseKeyPath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
}
var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
return token;
}
}
}
๐ง Explanation
Generates an OAuth2 access token using the service account JSON.
Sends a POST request to https://fcm.googleapis.com/v1/projects/{project_id}/messages:send.
The token, title, and body are passed dynamically.
๐งฎ Step 6. Create an API Controller
Create Controllers/NotificationController.cs:
using Microsoft.AspNetCore.Mvc;
using FirebasePushAPI.Models;
using FirebasePushAPI.Services;
namespace FirebasePushAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class NotificationController : ControllerBase
{
private readonly FirebaseService _firebaseService;
public NotificationController()
{
_firebaseService = new FirebaseService();
}
[HttpPost("send")]
public async Task<IActionResult> SendNotification([FromBody] FcmNotificationRequest request)
{
var result = await _firebaseService.SendNotificationAsync(request.Token, request.Title, request.Body, request.ImageUrl);
if (result)
return Ok(new { success = true, message = "Notification sent successfully" });
else
return BadRequest(new { success = false, message = "Failed to send notification" });
}
}
}
๐งช Step 7. Test API in Postman
POST URL
https://localhost:5001/api/notification/send
Request Body (JSON)
{"token": "DEVICE_FCM_TOKEN","title": "Welcome!","body": "Your registration was successful ๐","imageUrl": "https://yourdomain.com/welcome.png"}
Response
{"success": true,"message": "Notification sent successfully"}
โ
The notification should instantly appear on your mobile device or web app registered with Firebase.
โก Bonus: Sending to a Topic Instead of a Single Token
If you want to send to a topic (e.g., โnewsโ):
Replace this block:
token = token,
with:
topic = "news",
Then, your Firebase clients should subscribe to the topic using the FCM SDK.
๐ Subscribe to FCM Topics (Docs)
๐งฉ Common Errors & Fixes
| Error | Cause | Solution |
|---|
401 Unauthorized | Invalid service account or scope | Ensure correct JSON key and project ID |
404 Not Found | Wrong endpoint | Check FCM v1 API URL |
InvalidRegistration | Invalid device token | Ensure valid token from FCM SDK |
Permission denied | Missing Firebase Messaging permission | Check IAM roles in GCP Console |
๐ External References
Firebase Cloud Messaging v1 API Docs
Google OAuth2 Authentication for Service Accounts
Firebase Admin SDK Setup Guide
Send Messages with FCM REST API
๐ Conclusion
By integrating Firebase v1 API with your .NET Core Web API, you can deliver real-time push notifications to any platform โ securely and efficiently.
This modern approach replaces the old FCM server key method with OAuth2 tokens, offering better security and control for enterprise-grade applications.
Whether itโs order updates, chat alerts, or system notifications, Firebase + .NET Core makes it fast and reliable.