Author: Dasan | Date: April 11, 2025
Firebase Cloud Messaging (FCM) is a powerful service provided by Google to send push notifications across platforms. In this blog, you'll learn how to integrate Firebase with ASP.NET Core Web API to send push notifications to mobile or web clients.
public class NotificationModel
{
public string To { get; set; } // FCM Token
public string Title { get; set; }
public string Body { get; set; }
}
public class FcmService
{
private readonly string _serverKey = "YOUR_FIREBASE_SERVER_KEY";
private readonly string _fcmUrl = "https://fcm.googleapis.com/fcm/send";
public async Task SendNotificationAsync(NotificationModel model)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={_serverKey}");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var data = new
{
to = model.To,
notification = new
{
title = model.Title,
body = model.Body,
sound = "default"
}
};
var json = JsonSerializer.Serialize(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(_fcmUrl, content);
var responseString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception($"FCM error: {response.StatusCode} - {responseString}");
}
}
}
[Route("api/[controller]")]
[ApiController]
public class NotificationController : ControllerBase
{
private readonly FcmService _fcmService;
public NotificationController(FcmService fcmService)
{
_fcmService = fcmService;
}
[HttpPost("send")]
public async Task<IActionResult> SendNotification([FromBody] NotificationModel model)
{
await _fcmService.SendNotificationAsync(model);
return Ok(new { message = "Notification sent successfully!" });
}
}
appsettings.jsonIOptions<> or IConfiguration to inject it into your service/api/notification/send{
"to": "YOUR_DEVICE_FCM_TOKEN",
"title": "Hello!",
"body": "This is a test notification."
}
You've successfully set up FCM in ASP.NET Core Web API. With this setup, you can notify your users via mobile or web in real-time. In upcoming blogs, we’ll discuss how to use topics, schedule messages, and add retry logic for production environments.
Stay tuned! ✨