Integrating Firebase Notifications in ASP.NET Core Web API

Author: Dasan | Date: April 11, 2025

1. 🚀 Introduction

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.

2. 🔧 Prerequisites

3. 🔑 Get Firebase Server Key

  1. Go to Firebase Console
  2. Select your project → Project Settings → Cloud Messaging
  3. Copy the Server Key and Sender ID

4. 📬 Create Notification Model

public class NotificationModel
{
    public string To { get; set; } // FCM Token
    public string Title { get; set; }
    public string Body { get; set; }
}

5. 📡 Send FCM Notification Method

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}");
        }
    }
}

6. 🛠️ API Endpoint to Trigger Notification

[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!" });
    }
}

7. 🛡️ Secure Your Server Key

8. 📱 Test with Postman

{
  "to": "YOUR_DEVICE_FCM_TOKEN",
  "title": "Hello!",
  "body": "This is a test notification."
}

9. 🏁 Conclusion

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! ✨