我有测试代码
@page "/admin/userInfo"
@page "/admin"
@inherits OwningComponentBase<UserManager<IdentityUser>>
@inject AuthenticationStateProvider AuthenticationStateProvider
@functions
{
}
@code
{
public UserManager<IdentityUser> _userManager => Service;
public string userName; /* => AuthenticationStateProvider.GetAuthenticationStateAsync().Result.User.Identity.Name; */
public IdentityUser identity;
protected override async Task OnInitializedAsync(){
if (_userManager != null)
{
identity = await _userManager.FindByNameAsync(userName);
userName = "abcde";
}
Console.WriteLine("OnInitializedAsync");
}
}
<h4>User Information</h4>
<h2>User name: @userName</h2>
<h4>h4 tag</h4>
@* <p>@identity.UserName</p> *@
当我尝试获取身份值时,OnInitializedAsync 中的用户名或身份无法跟上创建的速度。我认为当 OnInitializedAsync 结束时 @userName 或 @identity.UserName 可以访问 html 标签。我该如何解决这个问题?谢谢你的帮助
我尝试获取一些在 OnInitializedAsync 方法中初始化的值,但方法的执行无法到达组件的创建。我该如何解决这个问题?
您可以尝试下面的代码:
@page "/admin/userInfo"
@page "/admin"
@inherits OwningComponentBase<UserManager<IdentityUser>>
@inject AuthenticationStateProvider AuthenticationStateProvider
@code
{
public UserManager<IdentityUser> _userManager => Service;
public string userName;
public IdentityUser identity;
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
userName = user.Identity.Name;
identity = await _userManager.FindByNameAsync(userName);
}
else
{
// Handle the case where the user is not authenticated if necessary
}
}
}
<h4>User Information</h4>
@if(identity != null)
{
<h2>User name: @identity.UserName</h2>
}
else
{
<p>User is not authenticated.</p>
}
<h4>h4 tag</h4>