我已经在我的ASP.NET Core应用程序中设置了外部登录(Google)。我发现很难在登录后获取用户名/电子邮件。我可以看到存储在Aspnetusers表中的电子邮件,但在任何地方都看不到用户名。
我搜索并找到了此代码:
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
,但这给了我用户ID,如表Aspnetusers中所示。ClaimTypes.Email
返回null,但该值存在于表中(可能是此电子邮件是其他的)。我想获取用户名和用户电子邮件。有可能吗?
您是否可以访问SignManager,还是可以注入它?如果是,那么这就是您将如何访问用户ID(用户名),电子邮件,&姓氏:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public MyController (
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager
)
{
_userManager = userManager;
_signInManager = signInManager;
}
public async Task<IActionResult> MyAction(){
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
string userId = info.Principal.GetUserId()
string email = info.Principal.FindFirstValue(ClaimTypes.Email);
string FirstName = info.Principal.FindFirstValue(ClaimTypes.GivenName) ?? info.Principal.FindFirstValue(ClaimTypes.Name);
string LastName = info.Principal.FindFirstValue(ClaimTypes.Surname);
}
}
getuserid扩展:
public static class ClaimsPrincipalExtensions
{
public static string GetUserId(this ClaimsPrincipal principal)
{
if (principal == null)
return null; //throw new ArgumentNullException(nameof(principal));
string ret = "";
try
{
ret = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}
catch (System.Exception)
{
}
return ret;
}
}