Firebase Cloud Messaging (FCM) is a cross-platform solution for sending messages reliably at no cost. If you’re developing a backend with ASP.NET Core Web API, this guide walks you through the process of sending push notifications via Firebase using the Admin SDK and an OAuth token.
Prerequisites
Before diving into the code, ensure the following:
- You have a Firebase project set up.
- ASP.NET Core Web API project is ready.
- A device or emulator is registered to receive FCM messages (i.e., has a valid token).
Step 1. Get Firebase Admin SDK Private Key
- Open your Firebase project at https://console.firebase.google.com.
- Click the gear icon next to "Project Overview" → Project settings.
- Navigate to the Service accounts tab.
- Under the Firebase Admin SDK, click Generate new private key.
- Download the JSON file and place it in your ASP.NET Core project directory (for example:
Keys/firebase-adminsdk.json
).
Step 2. Generate Google OAuth Access Token
To communicate securely with the FCM endpoint, you need an access token using the service account JSON file.
Use the following utility method (inside your GoogleAuth
class):
using Google.Apis.Auth.OAuth2;
using System.Threading.Tasks;
public static class GoogleAuth
{
public static async Task<string> GetAccessTokenAsync()
{
var credential = GoogleCredential.FromFile("Keys/firebase-adminsdk.json")
.CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
return accessToken;
}
}
Step 3. Create FCM Models
Add the following model classes to your project:
public class FCM_Message
{
public MessageContent? Message { get; set; }
}
public class MessageContent
{
public string Token { get; set; } = "your Token";
public NotificationContent? Notification { get; set; }
}
public class NotificationContent
{
public string Title { get; set; } = "Hello!";
public string Body { get; set; } = "Greetings From Developer";
public string Image { get; set; } = "Image URL";
}
Step 4. Implement the Web API Endpoint
Here’s the controller method to send the notification:
[HttpPost]
[Route("Send_Notification")]
public async Task<IActionResult> post_SendNotification([FromBody] FCM_Message fcmMessage)
{
try
{
string accessToken = await GoogleAuth.GetAccessTokenAsync();
if (fcmMessage?.Message?.Token == null)
{
return BadRequest("Invalid FCM message payload. Token is missing.");
}
JsonSerializerOptions options = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
using var httpClient = new HttpClient();
string jsonPayload = JsonSerializer.Serialize(fcmMessage, options);
var request = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/v1/projects/nmaui-234f4/messages:send")
{
Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json")
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return Ok("Notification Sent Successfully!");
}
else
{
string responseContent = await response.Content.ReadAsStringAsync();
return BadRequest(responseContent);
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Make sure to replace the projectId
in the URL (nmaui-234f4
) with your Firebase project ID.
Sample Request Payload (JSON)
You can test the API with tools like Postman using this body:
{
"message": {
"token": "YOUR_DEVICE_FCM_TOKEN",
"notification": {
"title": "Hello from .NET!",
"body": "This is a test notification.",
"image": "https://example.com/image.png"
}
}
}
Conclusion
Now you can send push notifications directly from your ASP.NET Core Web API to any device registered with Firebase Cloud Messaging. This setup is scalable, secure, and works seamlessly for both mobile and web platforms.
Implemented FCM push notifications in a .NET MAUI app and successfully integrated notification sending via ASP.NET Core Web API.Contact me if you need assistance!