Reputation: 4288
I read the blazor lifecycle doc but I am still not sure where I can put something that I absolutely have to have executed as the first thing on the page load.
For example:
I am implementing a simple login. I use localstorage to save the authenticated user with one of the object fields being the time inserted into local storage so I can compare it to DateTime.Now to see if the object expired should the user hit f5.
The comparison needs to happen as the very first thing on the page load. So I put it into the OnInitialized
of the layout page all my pages use. Issue is OnInitialized
of the child page gets called before OnInitialized
of the layout page and the child expects the user object to already be set to do it's thing.
LoggedIn (main layout)
@inherits LayoutComponentBase;
<!--- material frame --->
@Body
<!--- /material frame --->
@code
{
protected override void OnInitialized()
{
Console.WriteLine("parent");
}
}
Exams (child)
@layout WebApp.Shared.Layouts.LoggedIn;
<! --- stuff ----.
@page "/app/examinations"
<! --- /stuff ----.
}
@code {
protected override void OnInitialized()
{
Console.WriteLine("child");
}
}
Upvotes: 0
Views: 226
Reputation: 1146
OnInitialized
should not be used to handle authentication. However, Blazor has an authentication framework built in that you can take advantage of:
AuthenticationStateProvider
, overriding
GetAuthenticationStateAsync
with the logic that determines whether
or not your user is logged in. AuthenticationStateProvider
in your client-side startup [Authorize]
attribute to any page that requires a loginMicrosoft full documentation here
Upvotes: 1