Access AuthenticationState in Blazor Server to update components in a single place #25908
-
Is there a way that I can use in Blazor to check authentication state in one place such as MainLayout.razor, so that when you are navigating to a component I can invalidate state if token expired? For example if you use OnAfterRenderAsync it is too late because the page has already rendered. I do not want to be repeating the check on every component. So I want to know if there is a lifecycle function that gets called each time you navigate to a component where I can do something like this
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If you want to share common functionality across all pages, here are a couple of options: Option 1: Common base classIf you create a C# class that inherits from @inherits MyCustomBaseClass Then, in Option 2: In the routerIf you don't want to use inheritance, then you could use something like the following in <Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<MyRoutingMiddleware>
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</MyRoutingMiddleware>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router> All I've added here is @if (canShowDestination)
{
@ChildContent
}
else
{
<LayoutView Layout="@typeof(MainLayout)">
<h2>Checking...</h2>
</LayoutView>
}
@code {
bool canShowDestination;
[Parameter] public RenderFragment ChildContent { get; set; }
protected override async Task OnParametersSetAsync()
{
canShowDestination = false;
await DoTheAsyncThing();
canShowDestination = true;
}
private async Task DoTheAsyncThing()
{
// TODO: Whatever async thing you want here
await Task.Delay(2000);
}
} As you can see, every time you navigate this will call |
Beta Was this translation helpful? Give feedback.
If you want to share common functionality across all pages, here are a couple of options:
Option 1: Common base class
If you create a C# class that inherits from
ComponentBase
, then you can make all your.razor
components inherit from your custom class via:Then, in
MyCustomBaseClass
, you can override lifecycle events likeOnInitializedAsync
and put your common logic there.Option 2: In the router
If you don't want to use inheritance, then you could use something like the following in
App.razor
: