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
相关产品推荐
相关产品推荐

