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

AspNetCore中HttpGet获取当前登录Visitor遇空值错误

问题解决方案

1. 修复登录流程的Claims生成

登录时需确保ClaimsPrincipal中包含ClaimTypes.Name对应的用户标识,避免User.Identity.Name为空:

var visitor = await _userManager.FindByEmailAsync(model.Email);
var principal = await _signInManager.CreateUserPrincipalAsync(visitor);
// 手动补充用户名Claim(若自动生成的Principal未包含)
if (!principal.HasClaim(c => c.Type == ClaimTypes.Name))
{
    principal.Identities.First().AddClaim(new Claim(ClaimTypes.Name, visitor.UserName));
}
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);

2. 调整GetCurrentVisitor接口实现

放弃依赖User.Identity.Name,改用更可靠的用户ID查询:

[HttpGet]
public async Task<IActionResult> GetCurrentVisitor()
{
    var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
    if (string.IsNullOrEmpty(userId))
    {
        return Unauthorized();
    }
    var visitor = await _userManager.FindByIdAsync(userId);
    if (visitor == null)
    {
        return NotFound();
    }
    var dto = _mapper.Map<VisitorDto>(visitor);
    return Ok(dto);
}

3. 验证认证中间件配置顺序

确保UseAuthentication在UseAuthorization和路由中间件之前:

// Program.cs
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

4. 配置Swagger的认证支持

测试接口时需携带登录凭证,若使用Cookie认证,需在Swagger中启用Cookie支持:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Visitor API", Version = "v1" });
    c.AddSecurityDefinition("CookieAuth", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.ApiKey,
        Name = "Cookie",
        In = ParameterLocation.Header,
        Description = "携带登录后的Cookie进行认证"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "CookieAuth" }
            },
            Array.Empty<string>()
        }
    });
});

内容的提问来源于stack exchange,提问作者Himanshu Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:27:48