Attention: We are retiring the ASP.NET Community Blogs. Learn more >


"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.

19 Comments

  • Great guide, though I am getting hung up when trying to get this to run on my node.js server.

    Here is my code:

    router.post('/notify', (req, res) => {
    admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "<database>.firebaseio.com"
    });

    var registrationTokens = [
    'tokenFromIosApp'
    ];
    var payload = {
    data : {
    body : 'TEST'
    }
    };

    admin.messaging().sendToDevice(registrationTokens, payload)
    .then((response) => {
    console.log('Sent successfully.\n');
    console.log(response);
    res.status(statusCodes.Ok);
    res.json(response);
    })
    .catch((error) => {
    console.log('Sent failed.\n');
    console.log(error);
    res.status(statusCodes.InternalServerError);
    res.json(error);
    });
    });

    Thoughts?

  • How can we send notifications to a user segment via HTTP?

  • Hi,
    How to genetate FCM TOKEN?

  • This blog is very informative and an excellent post that gained a lot of information. Good job.

    https://espirittech.com/laravel-development-services/

  • Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

    https://espirittech.com/php-development/

  • This is a great post I saw, thanks for sharing. I really want to hope that you will continue to share great posts in the future.

    https://espirittech.com/dot-net-application-development-company/

  • I am impressed by the information that you have on this blog. Thanks for sharing.

    https://espirittech.com/delphi-development/

  • Excellent website. I was always checking this article, and I’m impressed! Extremely useful and valuable info specially the last part, I care for such information a lot. Thank you.

    https://espirittech.com/ui-ux-development-services/

  • This blog is very informative and an excellent post that gained a lot of information. Good job.

    https://espirittech.com/laravel-development-services/

  • Hi there, you have performed an excellent job. I will certainly dig it and individually suggest it to my friends. I’m confident they will be benefited from this website.

    https://espirittech.com/wordpress-development-services/

  • This was a wonderful post being shared. The entire content in this blog is extremely helpful for me and gave me a clear idea of the concepts.

    https://espirittech.com/php-development-services/

  • Nice blog. I finally found a great post here Very interesting to read this article and very pleased to find this site. Great work!

    https://espirittech.com/ui-ux-development-services/

  • This is a great post I saw, thanks for sharing. I really want to hope that you will continue to share great posts in the future.

    https://espirittech.com/best-node-js-development-services/

  • Nice blog. Thank you for sharing. The information you shared is very effective for learners, I have got some important suggestions from it

    https://espirittech.com/codeigniter-development-services/

  • Really enjoyed reading your article, the information you delivered in this post was damn good. Keep sharing your post with efficient news.

    https://espirittech.com/laravel-development-company/

  • Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

    https://espirittech.com/offshore-php-development/

  • Pro Function Sports Injury Clinic is a specialized physiotherapy clinic that focuses on treating sports injuries and promoting optimal physical function. The clinic offers personalized treatment plans, utilizing advanced techniques to aid recovery and enhance performance. Their team of skilled physiotherapists is dedicated to helping athletes and active individuals return to their peak condition safely and effectively.

  • Prepare for success with the HP HPE7-A01 Practice Exam. Designed to help you ace your HPE Aruba Certified Design Expert (ACDX) certification, this practice exam provides a comprehensive set of questions that mirror the real exam format. Boost your confidence and knowledge with detailed explanations and in-depth review of key topics, ensuring you’re fully prepared. With flexible study options and expert insights, the HP HPE7-A01 Practice Exam is your ultimate resource to mastering the material and achieving your certification goals.

  • Great article - short, to the point and without unnecessary theory. I was setting up push notifications for a small project on ASP.NET Core, and your example with Firebase really saved a lot of time. The part with generating a server key and setting up headers was especially helpful - before that, I was always getting 401 errors and didn't understand why. An interesting point: I learned about Firebase mechanics from a backend developer whom I accidentally crossed paths with on nastyhookups where there were <a href="https://www.nastyhookups.com/granny-hookup.html">gilf hook ups</a> (yes, the site is supposedly for dating, but the people there are different). We started a conversation, it turned out that he automates notifications for e-commerce, and recommended this article as a base. So now not only does push work for me, but unexpected tech connections are also made in the strangest places

Add a Comment

As it will appear on the website

Not displayed

Your website