0
votes

In server-side Blazor how can I redirect to .cshtml Login page from Blazor component(.razor)?

Login.cshtml (located in the ProjectRoot/Identity/Login folder)

    @page "/login"
            
    <p> I am login page </p>

Index.razor


    @page "/"
    @inject NavigationManager NavigationManager
    
    <AuthorizeView>
        <NotAuthorized>
            @if (true)
            {
                NavigationManager.NavigateTo("/login");
            }
        </NotAuthorized>
    </AuthorizeView>

Currently, with the above code, I get an exception: Microsoft.AspNetCore.Components.NavigationException. What is the proper way of referring to the .cshtml page?

1

1 Answers

1
votes

You can create a custom component that triggers a javascript redirect on initialization. Something like this

[Parameter]
public string Path { get; set; }
[Inject] private IJSRuntime JSRuntime { get; set; }
protected override async Task OnInitializedAsync()
{
  await JSRuntime.InvokeVoidAsync("BlazorHelpers.RedirectTo", Path);
}

Then in your page:

<AuthorizeView>
    <NotAuthorized>
        <RedirectTo Path="Something"></RedirectTo>
    </NotAuthorized>
</AuthorizeView>

And your Js would be like this:

window.BlazorHelpers = {       
    RedirectTo: function (path) {
        window.location = path;
    }
};