要在Blazor服务中获取Identity.Id,您可以使用以下步骤:
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
public class IdentityService
{
private readonly AuthenticationStateProvider _authenticationStateProvider;
public IdentityService(AuthenticationStateProvider authenticationStateProvider)
{
_authenticationStateProvider = authenticationStateProvider;
}
public string GetCurrentUserId()
{
var authenticationState = _authenticationStateProvider.GetAuthenticationStateAsync().Result;
var user = authenticationState.User;
if (user.Identity.IsAuthenticated)
{
return user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}
return null;
}
}
@inject IdentityService identityService
当前用户Id: @currentUserId
@code {
private string currentUserId;
protected override void OnInitialized()
{
currentUserId = identityService.GetCurrentUserId();
}
}
请注意,上述代码示例假设您已经设置了身份验证和授权功能,并且已经在应用程序中配置了用户标识。如果您还没有完成这些步骤,您需要根据您的具体需求进行配置和设置。