"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

Sending Push Notifications from ASP.Net Core using Google Firebase

Google Firebase is a platform that helps developers to build mobile and web application. Firebase offers several options for developers to build the apps such as authentication, real time notification, messaging and push notifications etc. Developers can use Google Firebase to develop both Android and iOS and web applications.

Recently I was engaged in a project where by the customer wanted to push messages to the mobile application from their website. For e.g. when a page is published in the website, a new product added or price changed for a product, customer wanted to send push notifications to the mobile applications in these events.

Google Firebase is chosen for the project as the platform to send messages to the application. In this article I am going to demonstrate how you can integrate Google Firebase with an ASP.Net Core application. Integrating Firebase or handling push messages in the Mobile application is not in the scope of this application.

As you may aware, the Firebase services can be accessed through Firebase console.

https://console.firebase.google.com/u/0/

You can create projects in Firebase and use them in the mobile applications. The mobile applications are developed using Google Firebase to handle the messaging part. Firebase supports message delivery to a topic where all devices subscribed the topic will receive the notification or to a particular device token.

For more information about topics, refer the following urls.

https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging

https://firebase.google.com/docs/cloud-messaging/android/topic-messaging

Both iOS and Android Mobile applications are developed to subscribe to a topic named “WebsiteUpdates”. The handling of push messages is developed inside the application. This article focused on how to send a push notification to the mobile applications using ASP.Net Core back end

Demo

In order to push the notifications to the mobile application, I created an ASP.Net Core(2.2) application using razor pages. I used Visual Studio 2019 for this. The article is divided in to three sections as below.

  1. Create an ASP.Net core project
  2. Get the private key file from Firebase console
  3. Send the push notification

Create an ASP.Net Core Application

From the Visual studio, select File -> New -> Project

The create new project wizard will appear. Select ASP.Net Core Web Application and click Next

clip_image001

Now enter the project name, Location of the project and solution name, and click on create button

clip_image003

Now you can select the project type, ASP.Net Core version. Chose the values as per the below diagram and click Create.

clip_image005

A project will be created with the details specified.

clip_image006

The recommended ways to access Firebase services from server is to use Firebase Admin SDK. The admin SDK is available in .Net and can be found in github.

https://github.com/firebase/firebase-admin-dotnet

The how to setup documentation of the Firebase Admin SDK can be found in the below link.

https://firebase.google.com/docs/admin/setup/

Now we are ready to Integrate Firebase and send our push notification. The first thing we need to do is to install the FirebaseAdmin Nuget package

From the Package Manager for the solution, search FirebaseAdmin and install the Firebase Admin Nuget package by Google.

clip_image008

If you want to install the package by package manager console, you can do that too.

clip_image010

Get the Firebase Private Key file

In order to use Firebase services from the code, we need to authenticate our application with Firebase. The recommended way to do this is to create a private key from the Firebase console and use the key in the application. Login to the Firebase Console, go to the project you created and select Project settings

clip_image012

Go to the service accounts tab of the Project settings, click on Generate new private key.

clip_image014

The private key must be kept confidential.

clip_image015

Once the key is generated, it will be downloaded as a .json file.

clip_image017

The file name is not important. I just renamed the file to Auth.json and uploaded it to the root of my Asp.Net Core application.

clip_image018

Send Push Notification

For the purpose of this demo, I am going to send a push notification from the get handler of the .Net Core application.

You need to import the following Namespaces to your application.

using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;

In the IndexModel class, declare two variables, one to store the HostingEnvironment and the other to store the result of the send operation.

private IHostingEnvironment env;
public string result;

From the constructor, get the HostingEnvironment using dependency injection(DI).

public IndexModel(IHostingEnvironment env)
{
     this.env = env;
}

The purpose of getting IHostingEnvironment is to get the path of the file that is placed in the application root. Another approach is to store this path in appsettings variable and retrieve it from there. In this case you don’t need the IHostingEnvironment variable.

Now see the Get Method code

         public async Task OnGetAsync()
         {
             var path = env.ContentRootPath;
             path = path + "\\Auth.json";
             FirebaseApp app = null;
             try
             {
                 app = FirebaseApp.Create(new AppOptions()
                 {
                     Credential = GoogleCredential.FromFile(path)
                 }, "myApp");
             }
             catch (Exception ex)
             {
                 app = FirebaseApp.GetInstance("myApp");
             }
 
             var fcm = FirebaseAdmin.Messaging.FirebaseMessaging.GetMessaging(app);
             Message message = new Message()
             {
                 Notification = new Notification
                 {
                     Title = "My push notification title",
                     Body = "Content for this push notification"
                 },
                 Data = new Dictionary<string, string>()
                 {
                     { "AdditionalData1", "data 1" },
                     { "AdditionalData2", "data 2" },
                     { "AdditionalData3", "data 3" },
                 },
 
                     Topic = "WebsiteUpdates"
             };
            
             this.result = await fcm.SendAsync(message);
         }

  • The method must be async as Firebase is using async method to send the message.
  • The path variable contains the path to the Auth.json file downloaded from Firebase
  • Try to create a Firebase app, if the app is already created, it will throw error. So if your application is already created an app, get the instance of that app.
  • Once App is created, get the messaging instance for the app
  • Create a message object by specifying the Notification and Data payloads.
  • The data payload can contain all your custom data that you want to pass it to the notification.
  • Specify the Topic for the message. The application must be subscribed to this in order to receive the push notification.
  • Once the message object is built, send it using the SendAsync method.
  • Send message to a specific App Instance

In order to send the message to a specific app instance, you just need to replace Topic with Token parameter. The token can contain a Firebase App token.

e.g.

var token = "eH1Syxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxx";
             Message message = new Message()
             {
                 Notification = new Notification
                 {
                     Title = "My push notification title",
                     Body = "Content for this push notification"
                 },
                 Data = new Dictionary<string, string>()
                 {
                     { "AdditionalData1", "data 1" },
                     { "AdditionalData2", "data 2" },
                     { "AdditionalData3", "data 3" },
                 },
                 Token = token
             };
         this.result = await fcm.SendAsync(message);

Now in the Index.cshtml file, I am just displaying the message.

@page
@model IndexModel
@{
     ViewData["Title"] = "Home page";
}
 
<div class="text-center">
     @Model.result
</div>

From Visual Studio, Run the application and the following is the output of the application.

image

The message contains the message id that is returned by the SendAsync method. Now the mobile application receives the message with notification and data payload.

Summary

By using ASP.Net you can build backend applications that can communicate with your mobile applications easily. Google Firebase offers cross platform message solutions that can be easily integrated with .Net applications.

16 Comments

Add a Comment

As it will appear on the website

Not displayed

Your website