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

Blazor WebAssembly应用点击忘记密码后返回登录页问题求助

Blazor WASM点击“忘记密码”跳转异常问题修复

问题

Blazor WebAssembly应用中,点击登录页的“忘记密码”按钮后,未跳转到Forgot Password页面,反而回到登录页。

核心原因

  1. 路由路径不匹配:Forgot Password页面的路由是/ForgotPass,但登录页跳转代码中使用的是/ForgotPassX,导致路由匹配失败,触发NotFound逻辑。
  2. MainLayout强制跳转逻辑无排除规则:MainLayout的OnParametersSetAsync方法中,只要用户未认证就强制跳转到登录页,且未排除登录、忘记密码这类无需授权的页面;同时NotFound部分使用MainLayout,进一步触发跳转。

修复步骤

1. 修正跳转路径

修改Login页面的跳转逻辑,确保目标路径与Forgot Password页面的路由一致:

@code {
    void ForgotPassword()
    {
        // 修正为正确的路由路径
        NavigationManager.NavigateTo("/ForgotPass", true);
    }   
}

2. 优化MainLayout的跳转逻辑

注入NavigationManager,添加路由排除规则,避免对无需授权的页面执行跳转:

@inherits LayoutComponentBase
@inject NavigationManager NavigationManager

<AuthorizeView>
    <Authorized>        
        <NavBar>
            <NavBarLeft>....
        </NavBar>
    </Authorized>
</AuthorizeView>

@code {
    [CascadingParameter]
    Task<AuthenticationState> AuthenticationState { get; set; }

    protected override async Task OnParametersSetAsync()
    { 
        navBarLeftInjectableMenu.SetContent(null, false);      
        var authState = await AuthenticationState;
        if (!authState.User.Identity.IsAuthenticated)
        {
            var currentPath = NavigationManager.Uri.ToLower();
            // 排除登录、忘记密码页面,避免误跳转
            if (!currentPath.Contains("/loginx") && !currentPath.Contains("/forgotpass"))
            {
                NavigationManager.NavigateTo("/LoginX");
            }
        }
    }
}

3. 调整NotFound布局

将NotFound部分的布局改为AuthLayout,避免触发MainLayout的强制跳转:

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>                  
                    <!-- 可选:添加未授权时的跳转逻辑 -->
                    @{ NavigationManager.NavigateTo("/LoginX"); }
                </NotAuthorized>
            </AuthorizeRouteView>
    </Found>
    <NotFound>    
            <LayoutView Layout="@typeof(AuthLayout)">              
                <p>页面未找到,请检查路径是否正确</p>
            </LayoutView>     
    </NotFound>
</Router>
</CascadingAuthenticationState>

额外检查

确保Forgot Password和Login页面正确指定@layout AuthLayout,避免意外使用MainLayout:

  • Forgot Password页面:@page "/ForgotPass" + @layout AuthLayout
  • Login页面:@page "/LoginX" + @layout AuthLayout

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:24:16