Home > Mobile >  (Blazor) NavigationManager is null?
(Blazor) NavigationManager is null?

Time:12-29

Attempting to get visitors that aren't logged in to be redirected to the login page. This is my Index.razor file:

@page "/"
@inject NavigationManager NavManager
@code {
    public Index() {
        if (Auth.isLoggedIn() == false)
        {
            NavManager.NavigateTo("/login");
        }
    }
}

This results in an

System.NullReferenceException: Object reference not set to an instance of an object.
   at PolAcaDossier.Pages.Index..ctor() in F:\dev\polacadossier\Pages\Index.razor:line 7

It seems to be working fine in another page. The implementation of that page is as follows:

@page "/account"
@inject NavigationManager NavManager

<br /><button  @onclick="logOut">Uitloggen</button>

@code {
    private void logOut() {
        if (!Auth.isLoggedIn()) return;
        Auth.logout();
        NavManager.NavigateTo("/login");
    }
}

I have tried googling to see if anyone else had the same issue, I've asked the question on a programming Discord server and I've tried implementing it on a new page. All without success.

CodePudding user response:

In Blazor components, dependency injection is done by the Renderer and takes place after the Renderer instantiates an instance of the component i.e. after any Ctor has run. You should not try to access any injected object until Attach is called on the instance by the Renderer. As you are unlikely to be using Attach or SetParametersAsync in any ComponentBase component, consider the first method where you can call injected properties as OnInitialized.

In the code you've provided above, the first block attempts to access the property prior to injection. In the second block you are accessing the property in a UI event which will be after the first render.

CodePudding user response:

Overlooking the obvious. You want to make the Index page force a login.

All you need to do is:

@using Microsoft.AspNetCore.Authorization;
@page "/"
@attribute [Authorize]

Try it!

  • Related