This is a quick post to show how you can add a couple of simple extension methods to the NavigationManager class in your Blazor WebAssembly app for accessing query string parameters in the URL.

Query String Extension Methods for Navigation Manager

The below extension methods use the HttpUtility.ParseQueryString() method to uri into a name value collection.

The first method returns the entire query string as a NameValueCollection that can then be accessed like an array (e.g. querystring["id"]), and the second method returns a single query string value.

using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Specialized;
using System.Web;

namespace BlazorApp.Helpers
{
    public static class ExtensionMethods
    {
        // get entire querystring name/value collection
        public static NameValueCollection QueryString(this NavigationManager navigationManager)
        {
            return HttpUtility.ParseQueryString(new Uri(navigationManager.Uri).Query);
        }

        // get single querystring value with specified key
        public static string QueryString(this NavigationManager navigationManager, string key)
        {
            return navigationManager.QueryString()[key];
        }
    }
}

Blazor get whole query string collection

This is how to get the entire querystring collection from the navigation manager and then get a single value from the collection.

var querystring = NavigationManager.QueryString();

// get id from query string
var id = querystring["id"];

#blazor #webassembly #blazor webassembly

Blazor WebAssembly - Get Query String Parameters with Navigation Manager
20.70 GEEK