You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Blazor项目中NavigationLock组件失效问题求助

.NET 8中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:10:21