我正在尝试使用 Blazor Web Apps 创建一个网站,其中包含可公开访问的页面和需要用户登录 (OpenID) 才能查看的页面。实现这一点的最干净的方法是什么。
一种方法是使用多个布局,其中我有一个 LoggedIn 布局和一个 LoggedOut 布局。
登录布局
/// <summary>
/// LoggedIn Layout
/// </summary>
protected async override Task OnInitializedAsync() {
// Load user
if (authenticationState is not null) {
//Check authentication state and store user
var authState = await authenticationState;
var user = authState?.User;
//Check if user is authenticated
if (user is not null) {
if (user.Identity is not null && user.Identity.IsAuthenticated) {
//Initialise current user service
this.CurrentUserService.Initialize(user.Claims);
//Return
return;
}
}
}
//Redirect user to login page
var challengeUri = "/login?redirectUri=" + System.Net.WebUtility.UrlEncode(NavigationManager.Uri);
NavigationManager.NavigateTo(challengeUri, true);
}
注销布局
/// <summary>
/// LoggedOut Layout
/// </summary>
private async Task LoadUser() {
// Load user
if (authenticationState is not null) {
//Check authentication state and store user
var authState = await authenticationState;
var user = authState?.User;
//Check if user is authenticated
if (user is not null) {
if (user.Identity is not null && user.Identity.IsAuthenticated) {
//Initialise current user service
this.CurrentUserService.Initialize(user.Claims);
}
}
}
}
这种方法的问题是,当我从 LoggedOut 页面切换到 LoggedIn 页面时,首先渲染页面,然后渲染新布局,然后再次渲染页面,这会触发异步数据库查询中的错误OnInitializedAsync 函数。
Invalid attempt to Read when reader is closed.
另一种方法是使用文档中描述的属性,但文档没有解释如何使多个页面可公开访问。 如有任何澄清,我们将不胜感激。
_Imports.razor
到 Private 并添加安全属性
@attribute [Authorize]
Private
中的所有页面现在都需要经过身份验证的用户。