.NET 8 Blazor项目中NavigationLock组件失效问题求助
方案一:改用手动订阅NavigationManager事件
由于.NET 8组件级交互式渲染模式下NavigationLock存在兼容性问题,可直接通过NavigationManager的LocationChanging事件实现相同逻辑,该方式在.NET 8中稳定生效:
@page "/counter" @rendermode InteractiveServer @inject IJSRuntime js @inject NavigationManager NavManager @implements IDisposable <PageTitle>Counter</PageTitle> <h1>Counter</h1> <p role="status">Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; private IDisposable? _navigationSubscription; protected override void OnInitialized() { // 订阅导航变更事件 _navigationSubscription = NavManager.LocationChanging += OnLocationChanging; } private async void OnLocationChanging(object? sender, LocationChangingEventArgs e) { var confirmed = await ShowConfirmationDialogAsync(); if (!confirmed) { // 阻止导航 e.PreventNavigation(); } } private void IncrementCount() { currentCount++; } private async Task<bool> ShowConfirmationDialogAsync() { return await js.InvokeAsync<bool>("confirm", "Caught this navigation event! Do you want to continue?"); } // 取消订阅,避免内存泄漏 public void Dispose() { _navigationSubscription?.Dispose(); } }
方案二:关闭增强导航(可选)
如果坚持使用NavigationLock组件,可尝试关闭.NET 8默认启用的增强导航功能,在Program.cs中修改配置:
builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddEnhancedNavigation(options => options.Enabled = false);
注意:关闭增强导航可能影响其他Blazor增强功能,需根据实际场景评估。
内容的提问来源于stack exchange,提问作者Mohammad Aldefrawy
相关产品推荐
相关产品推荐

