Reputation: 537
I have written a middleware class but currently only runs when I start the application, I want it to run every time the app navigates to a different page.
Thanks!
Upvotes: 1
Views: 1641
Reputation: 854
You have to use the NavigationManager.LocationChanged
event for this type of middleware as Blazor utilizes websockets to render the UI, not traditional HTTP requests which is what you were expecting. Example of MainLayout.razor
or any component that will only rendered once:
@implements IDisposable
@inject NavigationManager NavMgr
<h1>My Component</h1>
@code
{
public OnInitialized()
{
// Bind the LocationChanged event
NavMgr.LocationChanged += OnLocationChanged;
}
private void OnLocationChanged(object sender, LocationChangedEventArgs args)
{
// My code to execute when navigation has changed
}
public void Dispose()
{
// Always unbind the event on component disposal
NavMgr.LocationChanged -= OnLocationChanged;
}
}
Upvotes: 2