Get current Url in a Blazor component

asp.net-core blazor c#

Question

I need to know the url of the current page in order to check if I have to apply certain style to a element. The code below is an example.

@using Microsoft.AspNetCore.Blazor.Services
@inject IUriHelper UriHelper
@implements IDisposable

<h1>@url</h1>
<nav>
    <div class="nav-wrapper">
        <a href="#" class="brand-logo">Blazor</a>
        <ul id="nav-mobile" class="right hide-on-med-and-down">
            <li>
                <NavLink href="/" Match=NavLinkMatch.All>
                    Home
                </NavLink>
            </li>
            <li>
                <NavLink href="/counter">
                    Counter
                </NavLink>
            </li>
            <li>
                <NavLink href="/fetchdata">
                    Fetch data
                </NavLink>
            </li>
        </ul>
    </div>
</nav>

@functions {

    private string url = string.Empty;

    protected override void OnInit()
    {
        url = UriHelper.GetAbsoluteUri();
        UriHelper.OnLocationChanged += OnLocationChanged;
    }

    private void OnLocationChanged(object sender, string newUriAbsolute)
    {
        url = newUriAbsolute;
    }

    public void Dispose()
    {
        UriHelper.OnLocationChanged -= OnLocationChanged;
    }
}

I used the same approach used in the NavLink component in the Blazor repository, but it did not work. Any ideas?.

Popular Answer

There is no use in connecting to the OnLocationChanged event in a page or component, as they get loaded and disposed on demannd.

You should register to this event in app.cshtml as that won't be disposed.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow