ASP.NET Core Blazor Hybrid routing and navigation

Note

This isn't the latest version of this article. For the current release, see the .NET 8 version of this article.

Warning

This version of ASP.NET Core is no longer supported. For more information, see .NET and .NET Core Support Policy. For the current release, see the .NET 8 version of this article.

Important

This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

For the current release, see the .NET 8 version of this article.

This article explains how to manage request routing and navigation in Blazor Hybrid apps.

URI request routing behavior

Default URI request routing behavior:

  • A link is internal if the host name and scheme match between the app's origin URI and the request URI. When the host names and schemes don't match or if the link sets target="_blank", the link is considered external.
  • If the link is internal, the link is opened in the BlazorWebView by the app.
  • If the link is external, the link is opened by an app determined by the device based on the device's registered handler for the link's scheme.
  • For internal links that appear to request a file because the last segment of the URI uses dot notation (for example, /file.x, /Maryia.Melnyk, /image.gif) but don't point to any static content:
    • WPF and Windows Forms: The host page content is returned.
    • .NET MAUI: A 404 response is returned.

To change the link handling behavior for links that don't set target="_blank", register the UrlLoading event and set the UrlLoadingEventArgs.UrlLoadingStrategy property. The UrlLoadingStrategy enumeration allows setting link handling behavior to any of the following values:

  • OpenExternally: Load the URL using an app determined by the device. This is the default strategy for URIs with an external host.
  • OpenInWebView: Load the URL within the BlazorWebView. This is the default strategy for URLs with a host matching the app origin. Don't use this strategy for external links unless you can ensure the destination URI is fully trusted.
  • CancelLoad: Cancels the current URL loading attempt.

The UrlLoadingEventArgs.Url property is used to get or dynamically set the URL.

Warning

By default, external links are opened in an app determined by the device. Opening external links within a BlazorWebView can introduce security vulnerabilities and should not be enabled unless you can ensure that the external links are fully trusted.

API documentation:

The Microsoft.AspNetCore.Components.WebView namespace is required for the following examples:

using Microsoft.AspNetCore.Components.WebView;

Add the following event handler to the constructor of the Page where the BlazorWebView is created, which is MainPage.xaml.cs in an app created from the .NET MAUI project template.

blazorWebView.UrlLoading += 
    (sender, urlLoadingEventArgs) =>
    {
        if (urlLoadingEventArgs.Url.Host != "0.0.0.0")
        {
            urlLoadingEventArgs.UrlLoadingStrategy = 
                UrlLoadingStrategy.OpenInWebView;
        }
    };

Add the UrlLoading="Handle_UrlLoading" attribute to the BlazorWebView control in the .xaml file:

<blazor:BlazorWebView HostPage="wwwroot\index.html" 
    Services="{StaticResource services}" 
    x:Name="blazorWebView" 
    UrlLoading="Handle_UrlLoading">

Add the event handler in the .xaml.cs file:

private void Handle_UrlLoading(object sender, 
    UrlLoadingEventArgs urlLoadingEventArgs)
{
    if (urlLoadingEventArgs.Url.Host != "0.0.0.0")
    {
        urlLoadingEventArgs.UrlLoadingStrategy = 
            UrlLoadingStrategy.OpenInWebView;
    }
}

In the constructor of the form containing the BlazorWebView control, add the following event registration:

blazorWebView.UrlLoading += 
    (sender, urlLoadingEventArgs) =>
    {
        if (urlLoadingEventArgs.Url.Host != "0.0.0.0")
        {
            urlLoadingEventArgs.UrlLoadingStrategy = 
                UrlLoadingStrategy.OpenInWebView;
        }
    };

Get or set a path for initial navigation

Use the BlazorWebView.StartPath property to get or set the path for initial navigation within the Blazor navigation context when the Razor component is finished loading. The default start path is the relative root URL path (/).

In the MainPage XAML markup (MainPage.xaml), specify the start path. The following example sets the path to a welcome page at /welcome:

<BlazorWebView ... StartPath="/welcome" ...>
    ...
<BlazorWebView>

Alternatively, the start path can be set in the MainPage constructor (MainPage.xaml.cs):

blazorWebView.StartPath = "/welcome";

In the MainWindow designer (MainWindow.xaml), specify the start path. The following example sets the path to a welcome page at /welcome:

<blazor:BlazorWebView ... StartPath="/welcome" ...>
    ...
</blazor:BlazorWebView>

Inside the Form1 constructor of the Form1.cs file, specify the start path. The following example sets the path to a welcome page at /welcome:

blazorWebView1.StartPath = "/welcome";

This section explains how to navigate among .NET MAUI content pages and Razor components.

The .NET MAUI Blazor hybrid project template isn't a Shell-based app, so the URI-based navigation for Shell-based apps isn't suitable for a project based on the project template. The examples in this section use a NavigationPage to perform modeless or modal navigation.

In the following example:

In App.xaml.cs, create the MainPage as a NavigationPage by making the following change:

- MainPage = new MainPage();
+ MainPage = new NavigationPage(new MainPage());

Views/NavigationExample.xaml:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiBlazor"
             x:Class="MauiBlazor.Views.NavigationExample"
             Title="Navigation Example"
             BackgroundColor="{DynamicResource PageBackgroundColor}">
    <StackLayout>
        <Label Text="Navigation Example"
               VerticalOptions="Center"
               HorizontalOptions="Center"
               FontSize="24" />
        <Button x:Name="CloseButton" 
                Clicked="CloseButton_Clicked" 
                Text="Close" />
    </StackLayout>
</ContentPage>

In the following NavigationExample code file, the CloseButton_Clicked event handler for the close button calls PopAsync to pop the ContentPage off of the navigation stack.

Views/NavigationExample.xaml.cs:

namespace MauiBlazor.Views;

public partial class NavigationExample : ContentPage
{
    public NavigationExample()
    {
        InitializeComponent();
    }

    private async void CloseButton_Clicked(object sender, EventArgs e)
    {
        await Navigation.PopAsync();
    }
}

In a Razor component:

  • Add the namespace for the app's content pages. In the following example, the namespace is MauiBlazor.Views.
  • Add an HTML button element with an @onclick event handler to open the content page. The event handler method is named OpenPage.
  • In the event handler, call PushAsync to push the ContentPage, NavigationExample, onto the navigation stack.

The following example is based on the Index component in the .NET MAUI Blazor project template.

Pages/Index.razor:

@page "/"
@using MauiBlazor.Views

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<button class="btn btn-primary" @onclick="OpenPage">Open</button>

@code {
    private async void OpenPage()
    {
        await App.Current.MainPage.Navigation.PushAsync(new NavigationExample());
    }
}

To change the preceding example to modal navigation:

  • In the CloseButton_Clicked method (Views/NavigationExample.xaml.cs), change PopAsync to PopModalAsync:

    - await Navigation.PopAsync();
    + await Navigation.PopModalAsync();
    
  • In the OpenPage method (Pages/Index.razor), change PushAsync to PushModalAsync:

    - await App.Current.MainPage.Navigation.PushAsync(new NavigationExample());
    + await App.Current.MainPage.Navigation.PushModalAsync(new NavigationExample());
    

For more information, see the following resources:

App linking (deep linking)

It's often desirable to connect a website and a mobile app so that links on a website launch the mobile app and display content in the mobile app. App linking, also known as deep linking, is a technique that enables a mobile device to respond to a URI and launch content in a mobile app that's represented by the URI.

For more information, see the following articles in the .NET MAUI documentation: