I have a link in a side menu like this (Blazor Server):
<NotAuthorized>
<li class="nav-item px-3">
<NavLink class="nav-link" href="@($"LoginIDP?redirectUri=
{NavigationManager.Uri}")">
Login
</NavLink>
</li>
</NotAuthorized>
The idea is simple: I want to keep the redirectUri={NavigationManager.Uri}
part updated with the current Uri the user is on at all times, so no matter on which page/component the user clicks the login link, the correct redirectUri
is always passed to the login page.
But in reality, as the user clicks various other <NavLink>
on the page, the URI in the browser's address bar does change, so does the page content, but NavigationManager.Uri
remains the same unless I refresh the page.
Is this by design? How do I obtain the real current Uri without changing every link to some event call that forces updates?
When you click on a button, the page changes only the content, but the component where you render NavigationManager.Uri
isn't rerendered, so you probably need to rerender the component in some way to do that.
On way you can do that is to subscribe to the NavigationManager's LocationChanged event and call StateHasChanged
to rerender the component.
You can take a look at this example from the docs and modify it a little bit.
@implements IDisposable
@inject NavigationManager NavigationManager
@* Your component *@
<NotAuthorized>
<li class="nav-item px-3">
<NavLink class="nav-link" href="@($"LoginIDP?redirectUri=
{NavigationManager.Uri}")">
Login
</NavLink>
</li>
</NotAuthorized>
@code {
private void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
{
// rerender component
StateHasChanged();
}
protected override void OnInitialized()
{
// add to the NavigationManager event
NavigationManager.LocationChanged += HandleLocationChanged;
}
public void Dispose()
{
// remove from the NavigationManager event
NavigationManager.LocationChanged -= HandleLocationChanged;
}
}