简体   繁体   中英

(Blazor) NavigationManager is null?

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 class="btn-primary mt-3" @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.

In Blazor components, dependency injection is done by the Renderer and takes place after the Renderer instantiates an instance of the component ie 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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM