.NET MAUI Firebase database and API Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      10 mins read      Difficulty-Level: beginner

Explaining .NET MAUI Firebase Database and API in Detail for Beginners

Introduction to .NET MAUI

Before diving into Firebase and building a mobile application with .NET Multi-platform App UI (MAUI), it's essential to understand the basics of what .NET MAUI is.

.NET MAUI (Multi-platform App UI) is the evolution of Xamarin.Forms and aims to allow developers to build cross-platform applications for Android, iOS, Windows, Mac, and Tizen using C# and XAML. It is part of the .NET 6 and subsequent .NET versions.

What is Firebase?

Firebase is a comprehensive platform by Google that offers various back-end services, including Real-Time Database, Firestore, Authentication, Cloud Functions, and Cloud Messaging. It helps to build scalable applications quickly without setting up a server infrastructure.

For this guide, we will focus on integrating Firebase Real-Time Database and calling Firebase Cloud Functions (APIs) from a .NET MAUI application.

Prerequisites

  1. Install .NET MAUI SDK: Ensure you have the .NET SDK and MAUI workload installed on your development machine.
  2. Visual Studio or Visual Studio Code: Choose an IDE to develop your .NET MAUI project.
  3. Firebase Account: Set up a Firebase account and create a new Firebase project.

Integrating Firebase Real-Time Database with .NET MAUI

Step 1: Set Up Firebase Real-Time Database
  1. Log in to Firebase Console: Go to the Firebase Console.
  2. Create a New Project: Click on "Add Project" and follow the instructions to create a project. Once created, select "Realtime Database".
  3. Create Database: Click on "Create Database" and choose whether to start in test mode or production mode. For development, you can start in test mode.
  4. Get Database URL: Note down your database’s URL from the Real-Time Database section in the Firebase Console.
Step 2: Install Google Firebase NuGet Packages

In your .NET MAUI project, you need to add the following NuGet packages to install Firebase dependencies:

  • Firebase.Auth
  • Firebase.Storage
  • Firebase.Database
  • Xamarin.Firebase.Auth
  • Xamarin.Firebase.Database
  • Xamarin.GooglePlayServices.Auth
  • Xamarin.GooglePlayServices.Base

You can install these packages via the NuGet Package Manager in Visual Studio or by using the following command:

dotnet add package Firebase.Database
Step 3: Add Firebase Configuration Files

For iOS and Android, download the google-services.json (for Android) and GoogleService-Info.plist (for iOS) from the Firebase Console and add them to your respective projects.

For Android:
  • Place google-services.json in the Assets folder with a build action of GoogleServicesJson.
For iOS:
  • Place GoogleService-Info.plist in the root of your iOS project with a build action of BundleResource.
Step 4: Initialize Firebase in Your .NET MAUI Application

In your App.xaml.cs or Program.cs (depending on the version of .NET MAUI you are using), initialize Firebase in the MauiProgram.CreateMauiApp() method or the constructor of App.

using Firebase.Auth;
using Firebase.Database;
using Firebase.Storage;

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        });

#if ANDROID
    Firebase.FirebaseApp.InitializeApp(Android.App.Application.Context);
#elif IOS
    App.Configure();

    Firebase.Core.App.Configure();
#endif

    return builder.Build();
}

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    App.Configure();

    Firebase.Core.App.Configure();

    return base.FinishedLaunching(app, options);
}

public static class App
{
    public static void Configure()
    {
    }
}
Step 5: Creating a Data Model

Define a data model class that represents the data you want to store and retrieve from the database.

// Models/UserDataModel.cs
public class UserDataModel
{
    public string UserId { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public DateTime RegistrationDate { get; set; }
}
Step 6: Interacting with Firebase Real-Time Database

Here is an example of how to interact with Firebase Real-Time Database to create, read, update, and delete data.

Create Data
var firebaseDatabase = Firebase.Database.FirebaseDatabase.Instance;
var databaseReference = firebaseDatabase.GetReference("Users");

var newUser = new UserDataModel
{
    UserId = Guid.NewGuid().ToString(),
    Username = "johndoe",
    Email = "john.doe@example.com",
    RegistrationDate = DateTime.UtcNow
};

await databaseReference.Push().SetValueAsync(newUser);
Read Data
databaseReference.OrderByChild("Username").EqualTo("johndoe").AddChildEventListener(new ChildEventListenerImplementation());
public class ChildEventListenerImplementation : Java.Lang.Object, IChildEventListener
{
    public void OnCancelled(DatabaseError error)
    {
        Console.WriteLine("Read data unsuccessful!");
    }

    public void OnChildAdded(DataSnapshot snapshot, string previousChildKey)
    {
        var user = snapshot.GetValue<UserDataModel>();
        Console.WriteLine($"UserId: {user.UserId}, Username: {user.Username}, Email: {user.Email}, Registration Date: {user.RegistrationDate}");
    }

    public void OnChildChanged(DataSnapshot snapshot, string previousChildKey) { }

    public void OnChildMoved(DataSnapshot snapshot, string previousChildKey) { }

    public void OnChildRemoved(DataSnapshot snapshot) { }
}
Update Data
var userReference = databaseReference.Child("Users").Child(userId);
await userReference.UpdateChildrenAsync(new Dictionary<string, object>
{
    { "Email", "john.doe.updated@example.com" }
});
Delete Data
var userReference = databaseReference.Child("Users").Child(userId);
await userReference.RemoveValueAsync();

Integrating Firebase Cloud Functions with .NET MAUI

Firebase Cloud Functions allows developers to run backend code in response to events triggered by Firebase features and HTTPS requests. In this section, we will show you how to integrate a simple Firebase Cloud Function into your .NET MAUI application.

Step 1: Write a Firebase Cloud Function

Create a Firebase Cloud Function to demonstrate API integration. For this example, we will write a simple function that returns a greeting message.

// index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.helloWorld = functions.https.onRequest((request, response) => {
  functions.logger.info("Hello logs!", {structuredData: true});
  response.send(`Hello from Firebase Cloud Functions!`);
});
Step 2: Deploy Firebase Cloud Function
  1. Install Firebase CLI: Ensure you have the Firebase CLI installed.
  2. Initialize Firebase Functions:
    firebase init functions
    
  3. Deploy Function:
    firebase deploy --only functions
    
  4. Get URL: After deployment, you will get a URL for your helloWorld function.
Step 3: Call Firebase Cloud Function from .NET MAUI

Create an asynchronous method in your .NET MAUI application to call the Firebase Cloud Function using HttpClient.

using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

public class FirebaseService
{
    private readonly HttpClient _httpClient;

    public FirebaseService()
    {
        _httpClient = new HttpClient();
    }

    public async Task<string> CallFirebaseFunctionAsync()
    {
        var functionUrl = "https://us-central1-yourfirebaseproject.cloudfunctions.net/helloWorld";
        var response = await _httpClient.GetAsync(functionUrl);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }
        return null;
    }
}
Step 4: Integrate Firebase Cloud Function Call into Your Application

Use the FirebaseService class in your .NET MAUI application to call the Firebase Cloud Function.

public partial class MainPage : ContentPage
{
    private readonly FirebaseService _firebaseService;

    public MainPage()
    {
        InitializeComponent();
        _firebaseService = new FirebaseService();
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        var result = await _firebaseService.CallFirebaseFunctionAsync();
        if (!string.IsNullOrEmpty(result))
        {
            await DisplayAlert("Success", result, "OK");
        }
        else
        {
            await DisplayAlert("Error", "Failed to call Firebase function", "OK");
        }
    }
}

Summary

This guide walks you through setting up and integrating Firebase Real-Time Database and Cloud Functions into a .NET MAUI application. You learned how to:

  1. Create a Firebase project and set up the Real-Time Database.
  2. Initialize Firebase in your .NET MAUI project.
  3. Work with Firebase Real-Time Database operations like creating, reading, updating, and deleting data.
  4. Write and deploy a Firebase Cloud Function.
  5. Call the Firebase Cloud Function from your .NET MAUI application.

By following these steps, you can build a powerful, cross-platform mobile application that leverages the robust Firebase backend services. Happy coding!