Search code examples
c#asp.net-corerazorblazor

Get URL Params from route, without specifing @page route - Blazor


My component wants to access the route param Foo from the url www.url.com/test?Foo=bar. However, my component does not specify the @page "..." at the top of the .razor file.

I've tried accessing the param as following, without any success:

[SupplyParameterFromQuery]
public string? Foo{ get; set; }

...

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        Console.WriteLine(Foo); //outputs a blank line
    }
    ...
}

I am not sure, if the @page is the limitation, as I've read in some posts that this fixed the problem of others. Surely there must be a way to acess the url-param.


Solution

  • Use MyNavigationManager:

    
    @inject NavigationManager MyNavigationManager
    
    
    ...
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            Console.WriteLine(GetQueryParm("Foo")); //outputs a blank line
        }
        ...
    }
    
    string GetQueryParm(string parmName)
    {
        var uriBuilder = new UriBuilder(MyNavigationManager.Uri);
        var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
        return q[parmName] ?? "";
    }
    

    Credits to myself: NavigationManager - Get current URL in a Blazor component