Published: August 09 2020

Blazor WebAssembly - Get Query String Parameters with Navigation Manager

Built with ASP.NET Core Blazor WebAssembly 3.2.1

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 get single value from query string

This is how to get a single querystring value directly from the navigation manager in one step.

var id = NavigationManager.QueryString("id");

 


Need Some Blazor Help?

Search fiverr for freelance Blazor developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by