Exception shown while redirecting to the login page in Blazor Server

Mohammad Nasir Uddin 41 Reputation points
2022-08-26T19:55:39.517+00:00

I have created a Blazor Server project in .NET 6. I want to implement my own custom authentication in this project. So I have created a login component under Page folder. And I have configured my App.razor file below so that while not authenticated it redirects to the login page.

<CascadingAuthenticationState>  
    <Router AppAssembly="@typeof(App).Assembly">  
        <Found Context="routeData">  
            <AuthorizeView>  
                <Authorized>  
                    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />  
                    <FocusOnNavigate RouteData="@routeData" Selector="h1" />  
                </Authorized>  
                <NotAuthorized>  
                    <LoginRedirect></LoginRedirect>  
                </NotAuthorized>  
            </AuthorizeView>  
        </Found>     
          
        <NotFound>  
            <PageTitle>Not found</PageTitle>  
            <AuthorizeView>  
                <Authorized>  
                    <LayoutView Layout="@typeof(MainLayout)">  
                        <p role="alert">Sorry, there's nothing at this address.</p>  
                    </LayoutView>  
                </Authorized>  
                <NotAuthorized>  
                    <LoginRedirect></LoginRedirect>  
                </NotAuthorized>  
            </AuthorizeView>  
        </NotFound>  
    </Router>  
</CascadingAuthenticationState>  

Here is my LoginRedirect component code:

using Microsoft.AspNetCore.Components;  
  
namespace BlazorJwtToken.Shared  
{  
    public partial class LoginRedirect  
    {  
        [Inject] NavigationManager? NavigationManager { get; set; }  
        protected override Task OnInitializedAsync()  
        {  
            var returnUrl = "/" + NavigationManager?.ToBaseRelativePath(NavigationManager.Uri);  
              
            NavigationManager?.NavigateTo($"/login?returnUrl={returnUrl}", false);  
  
            return Task.CompletedTask;  
        }  
    }  
}  

But when I run the project it hits the OnInitializedAsync function of LoginRedirect component and throws the below exception:

235313-image.png

235180-image.png

Can anyone tell me how to solve the problem?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,371 questions
{count} votes