我正在制作扩展程序以获取用户电子邮件,但我无法参考ApplicationDbContext
服务。
public static class Extensions
{
// private static readonly ApplicationDbContext _dbContext;
// static Extensions(ApplicationDbContext dbContext)
// {
// _dbContext = dbContext;
// }
public static string GetUserEmail(this ClaimsPrincipal principal)
{
string email = string.Empty;
string userid = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "";
if (!string.IsNullOrEmpty(userid))
{
email = _dbContext.Users.Single(x => x.Id == userid).Email;
}
return email;
}
}
用途:
string email = User.GetUserEmail();
但静态类不能包含任何参数。另外,我不想将dbContext
作为参数传递给GetUserEmail
方法。
还有其他办法吗?
答案 0 :(得分:1)
使用usermanager获取该信息
// Inject UserManager<IdentityUser> into your controller or service
var user = await userManager.GetUserAsync(this.User); // pass ClaimsPrincipal
var email = await usermanager.GetEmailAsync(user);
答案 1 :(得分:-2)
你能使用静态初始化方法吗?
public class Extensions
{
private static ApplicationDbContext _dbContext { get; set; }
public static void Init(ApplicationDbContext dbContext)
{
this._dbContext = dbContext;
}
}
<强>用法强>
Extensions.Init(dbContext);
var email = User.GetEmail();