I'm trying out Blazor ServerSide and created a Component to Redirect To the Login Page when a user is not logged in.
@inject Microsoft.AspNetCore.Components.NavigationManager NavigationManager;
@code {
/// <inheritdoc />
protected override Task OnInitializedAsync()
{
NavigationManager.NavigateTo("Login");
return Task.CompletedTask;
}
}
But always when "NavigateTo" is called the following exception is thrown:
"Microsoft.AspNetCore.Components.NavigationException: Exception of type 'Microsoft.AspNetCore.Components.NavigationException' was thrown.
at Microsoft.AspNetCore.Components.Server.Circuits.RemoteNavigationManager.NavigateToCore(String uri, Boolean forceLoad)
at Microsoft.AspNetCore.Components.NavigationManager.NavigateTo(String uri, Boolean forceLoad)
at ApplySupportTool.Blazor.Pages.RedirectToLogin.OnInitializedAsync() in C:\\Users\\padruttn\\Documents\\git\\ApplySupportTool\\src\\ApplySupportTool.Blazor\\Pages\\RedirectToLogin.razor:line 8"
Interesstingly the navigation is made despite the exception. I also tried to call it with the path "/login" but the same behaviour here.
Inject NavigationManager in razor. Use Uri from NavigationManager to get the current URL.
You can redirect to a page in Blazor using the Navigation Manager's NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.
Access to browser navigation from Blazor is provided via the NavigationManager service. This can be injected into a Blazor component using @inject in a razor file, or the [Inject] attribute in a CS file. The NavigationManager service has two members that are of particular interest; NavigateTo and LocationChanged .
There is an open issue on github for this problem. See also the preceeding issue where a possible workaround is mentioned: putting the NavigateTo
method into OnAfterRender
instead of OnInitialized
.
I needed to put this into OnInitialized
rather than OnAfterRender
, so had to go with the render-mode="Server"
method, though apparently this isn't recommended.
It also states in the GitHub issue that this only happens in debug, not release, so a middle ground option is to change _Host.cshtml
to contain:
<environment include="Staging,Production">
<component render-mode="ServerPrerendered" type="typeof(App)" />
</environment>
<environment include="Development">
<component render-mode="Server" type="typeof(App)" />
</environment>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With