You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server应用中不使用AuthenticationStateProvider获取当前用户ID

Blazor Server 中获取登录用户ID的正确方式

你的问题核心在于GetCurrentLoggedInUserIdAsync方法没有实际获取登录用户的认证信息,只是返回了传入的空值。在Blazor Server环境下,正确使用AuthenticationStateProvider获取用户ID的方案如下:

1. 注入认证服务

在组件的@code块顶部注入AuthenticationStateProvider:

[Inject]
private AuthenticationStateProvider AuthStateProvider { get; set; } = default!;

2. 实现用户ID获取逻辑

替换原有的空实现,从认证状态中解析用户的Claims信息:

private async Task<int> GetCurrentLoggedInUserIdAsync()
{
    var authState = await AuthStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;

    if (!user.Identity?.IsAuthenticated ?? true)
    {
        throw new UnauthorizedAccessException("用户未登录");
    }

    // 默认Identity框架用ClaimTypes.NameIdentifier存储用户ID,若你用了自定义Claim类型请替换
    var userIdClaim = user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
    if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
    {
        throw new InvalidOperationException("无法获取用户ID");
    }

    return userId;
}

3. 修改调用逻辑

调用时无需传入参数,直接调用新实现的方法:

int loggedInUserId = await GetCurrentLoggedInUserIdAsync();

完整修改后的代码示例

@code {
    [Inject]
    private AuthenticationStateProvider AuthStateProvider { get; set; } = default!;
    [Inject]
    private NavigationManager Navigation { get; set; } = default!;
    [Inject]
    private DatingAppService DatingAppService { get; set; } = default!;

    private string FullName { get; set; } = string.Empty;
    private DateTime Birthday { get; set; }
    private string Gender { get; set; } = "Male";
    private string City { get; set; } = string.Empty;
    private string PostalCode { get; set; } = string.Empty;
    private int Height { get; set; }
    private bool? ProfileCreated { get; set; }
    private string? ErrorMessage { get; set; }

    private async Task CreateProfileAsync()
    {
        try
        {
            int loggedInUserId = await GetCurrentLoggedInUserIdAsync();

            bool success = await DatingAppService.CreateProfile(loggedInUserId, FullName, Birthday, Gender, City, PostalCode, Height);

            if (success)
            {
                ProfileCreated = true;
                ErrorMessage = string.Empty;
                Navigation.NavigateTo("/like-profile", forceLoad: true);
            }
            else
            {
                ProfileCreated = false;
                ErrorMessage = "Profile creation failed.";
            }
        }
        catch (UnauthorizedAccessException)
        {
            ProfileCreated = false;
            ErrorMessage = "请先登录";
            Navigation.NavigateTo("/login");
        }
        catch (Exception ex)
        {
            ProfileCreated = false;
            ErrorMessage = "An error occurred: " + ex.Message;
        }
    }

    private async Task<int> GetCurrentLoggedInUserIdAsync()
    {
        var authState = await AuthStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (!user.Identity?.IsAuthenticated ?? true)
        {
            throw new UnauthorizedAccessException("用户未登录");
        }

        var userIdClaim = user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
        {
            throw new InvalidOperationException("无法获取用户ID");
        }

        return userId;
    }

    private string ProfileStatusColor => ProfileCreated.Value ? "profile-success" : "profile-error";
    private string ProfileStatusMessage => ProfileCreated.Value ? "Profile created successfully!" : ErrorMessage;
}

内容的提问来源于stack exchange,提问作者Adel Aj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 04:35:35