我有一个 Blazor WASM 应用程序,其页面 (/upload) 只能由经过身份验证的用户访问。该页面标有 @attribute [Authorize]
当我直接启动这个页面并且没有用户登录时,一切都按预期工作(重定向到 root)。
但是当我使用菜单导航到页面之后用户在另一个浏览器标签中注销时,页面被加载并且我的代码在{{1} } 被执行,它抛出一个异常,因为没有用户登录。导航是通过 OnInitializedAsync()
标签
为什么用户没有被重定向到 root,我如何全局设置用户应该被重定向到 root(而不是每页)?
答案 0 :(得分:0)
这已经被问到了,但别担心,我知道你!更新您的 App.razor
页面以处理授权检查:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@if (context.User.Identity != null && !context.User.Identity.IsAuthenticated)
{
<RedirectToLogin />
}
else
{
<p>You are not authorized to access this resource.</p>
}
</NotAuthorized>
<Authorizing>
<Loader />
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<div class="row justify-content-center">
<div class="col text-center">
<h2>Looks like you're lost, we didn't find anything at this location.</h2>
<p>Try navigating to the Dashboard or going back in the browser.</p>
</div>
</div>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>