Skip to content

[Blazor] Support state within NavigationManager #42617

@javiercn

Description

@javiercn

Adds support for passing state during navigations via navigation manager and updates the authentication infrastructure to make use of it.

The previous authentication infrastructure implementation used JS interop and sessionStorage and the URL query string to pass data between authentication states.

This was brittle and required extra work to avoid things like CSRF logouts or to encode/decode error messages on the error UI states.

The new NavigationManager API simplifies associating a state that is associated with the navigation entry and not with the session (like sessionStorage) and allows simple communication between different pages with the benefit that there is no cleanup needed.

Part of the improvements on the auth system are going to rely on this to pass data from other pages to the authentication pages, but since this change is general purpose and a net positive, I separated it into its own PR.

public abstract class NavigationManager 
{
+    public string? HistoryEntryState { get; protected set; }
}

public readonly struct NavigationOptions
{
+    public string? HistoryEntryState { get; init; }
}

public class LocationChangedEventArgs : EventArgs
{
+    public string? HistoryEntryState { get; }
}

public static class JSInteropMethods
{
+    /// <summary>
+    /// For framework use only.
+    /// </summary>
+    [JSInvokable(nameof(NotifyLocationChanged))]
+    public static void NotifyLocationChanged(string uri, string? state, bool isInterceptedLink)
}

Typical usage is:
From a component someone navigates in and pass in the associated state:

navigationManager.NavigateTo("/orders", new NavigationOptions { State = "My state" });

Another component can then retrieve the state

var state = navigationManager.State;
if(state){
...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-blazorIncludes: Blazor, Razor Components

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions