Firebase Notification In .Net Core

In this, article we are going to learn how to send push notifications using FCM from .Net Core web API.

We will also learn how to create a firebase project and how to get the server key and sender Id step by step.

What is FCM?

Firebase Cloud Messaging is a free cloud service from Google that allows users to send notifications and messages to another user.
It is a cross-platform messaging solution. you’ll send notifications and messages across a variety of platforms, as well as a golem, iOS, and net applications.

First, create a firebase project.

Go to firebase click on this link add a new project.

Second, provide the project name as per your choices.

Then click on the continue button goto next.

Once the project is ready and redirects to the dashboard then go to the project setting.

Then you can see your Sender ID and Server key as you can see in the below image.

How to send FCM firebase notification from a .NET Core Web API project.

Create a new project.

Open the project and install the following packages.

  • Install-Package CorePush
  • Install-Package Newtonsoft.Json
  • Install-Package Swashbuckle.AspNetCore

Then Open appsettings.json and add the Sender ID and Server Key in it.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "FcmNotification": {
    "SenderId": "Sender ID",
    "ServerKey": "Server Key"
  },
  "AllowedHosts": "*"
}

Create a models folder and add a new class FcmNotificationSetting then paste the below code in it.

public class FcmNotificationSetting
{
   public string SenderId { get; set; }
   public string ServerKey { get; set; }
}

Create NotificationModel class in the same folder and paste the below code in it.

using Newtonsoft.Json;

namespace FireBaseNotification.Models
{
  public class NotificationModel
  {
    [JsonProperty("deviceId")]
    public string DeviceId { get; set; }
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("body")]
    public string Body { get; set; }
  }
  public class GoogleNotification
  {
    public class DataPayload
    {
      [JsonProperty("title")]
      public string Title { get; set; }
      [JsonProperty("body")]
      public string Body { get; set; }
    }
    [JsonProperty("priority")]
    public string Priority { get; set; } = "high";
    [JsonProperty("data")]
    public DataPayload Data { get; set; }
    [JsonProperty("notification")]
    public DataPayload Notification { get; set; }
  }
}

Create another class ResponseModel and paste the below code into it.

public class ResponseModel
{
   [JsonProperty("isSuccess")]
   public bool IsSuccess { get; set; }
   [JsonProperty("message")]
   public string Message { get; set; }
}

Create Service folder in that create NotificationService class and paste the below code in it.

using CorePush.Google;
using FireBaseNotification.Models;
using FireBaseNotification.Service.IServices;
using Microsoft.Extensions.Options;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using static FireBaseNotification.Models.GoogleNotification;

namespace FireBaseNotification.Service
{
  public class NotificationService : INotificationService
  {
    private readonly FcmNotificationSetting _fcmNotificationSetting;
    public NotificationService(IOptions<FcmNotificationSetting> settings)
    {
      _fcmNotificationSetting = settings.Value;
    }

    public async Task<ResponseModel> SendNotification(NotificationModel notificationModel)
    {
      ResponseModel response = new ResponseModel();
      try
      {
        FcmSettings settings = new FcmSettings()
        {
          SenderId = _fcmNotificationSetting.SenderId,
          ServerKey = _fcmNotificationSetting.ServerKey
        };
        HttpClient httpClient = new HttpClient();

        string authorizationKey = string.Format("keyy={0}", settings.ServerKey);
        string deviceToken = notificationModel.DeviceId;

        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authorizationKey);
        httpClient.DefaultRequestHeaders.Accept
                .Add(new MediaTypeWithQualityHeaderValue("application/json"));

        DataPayload dataPayload = new DataPayload();
        dataPayload.Title = notificationModel.Title;
        dataPayload.Body = notificationModel.Body;

        GoogleNotification notification = new GoogleNotification();
        notification.Data = dataPayload;
        notification.Notification = dataPayload;

        var fcm = new FcmSender(settings, httpClient);
        var fcmSendResponse = await fcm.SendAsync(deviceToken, notification);

        if (fcmSendResponse.IsSuccess())
        {
          response.IsSuccess = true;
          response.Message = "Notification sent successfully";
          return response;
        }
        else
        {
          response.IsSuccess = false;
          response.Message = fcmSendResponse.Results[0].Error;
          return response;
        }
      }
      catch (Exception ex)
      {
        response.IsSuccess = false;
        response.Message = "Something went wrong";
        return response;
      }
    }
  }
}

Create the INotificationService interface and paste the below code into it.

public interface INotificationService
{
  Task<ResponseModel> SendNotification(NotificationModel notificationModel);
}

Create NotificationController in the controller folder and paste the below code into it.

using FireBaseNotification.Models;
using FireBaseNotification.Service.IServices;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace FireBaseNotification.Controllers
{
  [Route("api/[controller]")]
  [ApiController]
  public class NotificationController : ControllerBase
  {
    private readonly INotificationService _notificationService;
    public NotificationController(INotificationService notificationService)
    {
      _notificationService = notificationService;
    }

    [Route("sendnotification")]
    [HttpPost]
    public async Task<IActionResult> SendNotification(NotificationModel notificationModel)
    {
      var result = await _notificationService.SendNotification(notificationModel);
      return Ok(result);
    }
  }
}

Open the Startup file and paste the below code in ConfigureServices.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddTransient<INotificationService, NotificationService>();
    services.AddHttpClient<FcmSender>();
    services.AddHttpClient<ApnSender>();

    var appSettingsSection = Configuration.GetSection("FcmNotification");
    services.Configure<FcmNotificationSetting>(appSettingsSection);
}

That’s it

Now call your API using postman.

Output

Also, Check Read And Modify appsettings.json File In .Net Core

1 Comment

  1. Raheel Ahmed

    Hey,
    Can you please let me know how to find that device ID that you sent in the postman request ?

    0
    0
    Reply

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories