Platform code in Blazor Hybrid

March 17th 2023 Blazor .NET MAUI

The new Blazor Hybrid hosting model allows seamless execution of native platform code from Blazor pages and components. This is also made clear in the official documentation:

Components don't run in the browser, and WebAssembly isn't involved. Razor components load and execute code quickly, and components have full access to the native capabilities of the device through the .NET platform.

Surprisingly, I could not find an example or tutorial for this, so I decided to create one myself. I implemented the same functionality as in my TypeScript interop blog post, i.e. a page that displays the current location. However, instead of using the browser's geolocation API, I used the MAUI wrapper for the native geolocation API.

I started with the .NET MAUI Blazor App project template, which sets up a working Blazor project with support for 5 different platforms: Android, iOS, macOS, Tizen and Windows. According to the documentation, the geolocation API works on 4 of these platforms. Tizen is not listed and I have no way to test it.

Although it may seem unintuitive, you can call native APIs directly from the page code, as this code is executed natively and not as WebAssembly within the browser (or in this case, a web view). I called the API during the initialization of the page:

private Location geolocation;

protected override async Task OnInitializedAsync()
{
    try
    {
        var request = new GeolocationRequest(
            GeolocationAccuracy.Medium,
            TimeSpan.FromSeconds(10));
        geolocation = await Geolocation.Default.GetLocationAsync(request);
    }
    catch
    { }

    await base.OnInitializedAsync();
}

The page then simply displays the value stored in geolocation. For this to work, you also need to add some platform-specific settings, as documented. And give the application permission to access the location when it runs.

You can find the full working project with this code in my GitHub repository. The last commit clearly shows what I had to change in the project created by the template to make everything work.

In a Blazor Hybrid, you can easily make native calls from anywhere in the code. It's that simple. That might be why it's hard to find documentation or a tutorial on it. Still, it might not be obvious to everyone, especially if you already have experience with other Blazor hosting models.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License