我创建了一个测试应用程序来展示使用 Blazor Hybrid 与 .NET MAUI(.net 9)以及用户的AuthenticationState 时出现的问题。
我在 github 上的测试项目:https://github.com/tPeif/blazorhybrid_authProblem
有两个组件ArticleCategoryComponentExtra
和ArticleCategoryHtmlComponent
。内容包裹在 中AuthorizeView
。两个组件都显示现有文章类别的列表,并应显示一个弹出窗口ArticeCategory
,通过单击 id 为 的按钮来添加新类别addCategorybtn
。
完成模式并单击保存按钮后,SaveDetail
将调用该函数。
private async Task SaveDetail()
{
// user is logged in
var ok = await CheckAuthentication();
try
{
await ArticleCategoryService.Add(_selectedDetail);
// user is logged in
var ok1 = await CheckAuthentication();
await Load();
// user is logged in
var ok2 = await CheckAuthentication();
ShowCategoryDetail = false;
var ok3 = await CheckAuthentication();
}
catch (Exception ex)
{
string action = _selectedDetail.Id == 0 ? "add" : "update";
_logger.LogError(ex, "Cannot {action} the category '{categoryName}'", action, _selectedDetail.Name);
}
}
[Inject]
public AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;
private async Task<bool> CheckAuthentication()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (!user.Identity.IsAuthenticated)
{
// Redirect to login or show an error message
_logger.LogError("User not logged in anymore");
return false;
}
return true;
}
如你所见,我多次检查当前的 authenticationState。函数结束时,用户已登录,模态框被移除。
页面生命周期事件被调用多次以更新页面,但某一时刻 OnInitialized 再次被调用,这意味着(至少对我来说)页面被完全重新渲染,而这是用户不再登录的时刻。
有谁知道为什么应用程序会这样运行以及我应该怎么做才能避免用户注销?
问题是,当您关闭对话框组件时,应用程序会重置。向表单添加一个 guid Id,您将看到每次单击对话框中的“保存”按钮时都会获得一个新实例。
这确实让我困惑了一段时间,直到我看到了 html
form
标签。实际情况是,当你点击按钮时,表单会被回发到服务器。移除
form
,或者将按钮类型设置为type="button"
,问题就解决了。不再回发。您可能应该使用
EditForm
。