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

VS2022中ASP.NET Core 6 MVC的User.FindFirstValue(ClaimTypes.Email)返回Null

解决ASP.NET 6 MVC中ClaimTypes.Email返回Null的问题

问题根源

.NET 6对身份认证的默认配置做了调整,不再像.NET 5那样自动将用户邮箱作为ClaimTypes.Email声明注入到用户身份标识中,这是导致代码在.NET 6环境下失效的核心原因。

解决方案

1. 调整身份认证配置(Program.cs)

在Program.cs的身份服务配置中,显式指定使用自定义声明工厂来补充邮箱声明:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();

2. 实现自定义声明工厂

创建一个继承自UserClaimsPrincipalFactory的类,手动将用户邮箱添加到声明集合中:

public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser>
{
    public CustomUserClaimsPrincipalFactory(UserManager<IdentityUser> userManager, 
        IOptions<IdentityOptions> optionsAccessor) 
        : base(userManager, optionsAccessor)
    {
    }

    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(IdentityUser user)
    {
        var identity = await base.GenerateClaimsAsync(user);
        // 当用户邮箱不为空时添加声明
        if (!string.IsNullOrEmpty(user.Email))
        {
            identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
        }
        return identity;
    }
}

3. 自定义登录场景的处理

如果是PayPal回调这类自定义登录逻辑,需要在生成用户身份标识时直接显式添加邮箱声明:

// 假设已获取到用户ID和邮箱信息
var claims = new List<Claim>
{
    new Claim(ClaimTypes.NameIdentifier, userId),
    new Claim(ClaimTypes.Email, userEmailAddress)
};

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

4. 基础检查

  • 确认AspNetUsers表中对应用户的Email字段存在有效值
  • 若配置了RequireConfirmedAccount = true,需确保用户邮箱已完成验证

内容的提问来源于stack exchange,提问作者Ali Raza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:20:36