[英]ASP.NET Web Forms get current user email and assigning data on user identity
我正在构建一个使用ASP身份验证的Web窗体网站和两个用于存储数据的数据库。 当用户注册它在这两个表上创建记录时,这是我的register.aspx C#代码:
if (result.Succeeded)
{
infoLicencia.license_activations++;
res_users regUser = new res_users
{
branch_gkey = infoLicencia.branch_gkey,
licence_gkey = infoLicencia.license_gkey,
activo = true,
fecha_registro = DateTime.Now,
email = user.Email
};
db.res_users.Add(regUser);
db.SaveChanges();
// Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
//string code = manager.GenerateEmailConfirmationToken(user.Id);
//string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
//manager.SendEmail(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>.");
signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
这工作正常,但现在我需要检索存储在其他数据库上的数据,并使其可用于用户会话。
我在IdentityModels.cs上试过这个:
public class ApplicationUser : IdentityUser
{
public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
{
// Tenga en cuenta que authenticationType debe coincidir con el valor definido en CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
// Agregar reclamaciones de usuario personalizadas aquí
var Database2 = new PPublicEntities();
var UserData = Database2.res_users.Single(i => i.email == Email);
userIdentity.AddClaim(new Claim("BranchId", UserData.branch_gkey.ToString()));
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}
但是这个Email属性为null,我需要当前用户的电子邮件来搜索其他数据库中的数据。 我以为这个Email属性在登录时填充,我真的不知道该怎么做,为什么所有索赔值必须是String? 我真的希望它可以是一个长型。
默认情况下,用户电子邮件未在身份验 我们必须明确地将其添加为以下代码段。
userIdentity.AddClaim(new Claim(Constants.EmailClaimType, "User Email", ClaimValueTypes.String));
您还可以编写一个小方法来检索当前用户声明信息。 电邮:
public static string GetCurrentUserEmail()
{
var userEmail = string.Empty;
var claimIdentity = new ClaimsIdentity(Thread.CurrentPrincipal.Identity);
var userEmailClaim = claimIdentity.Claims.FirstOrDefault(x => x.Type == IdentityConstants.EmailClaimType);
if (userEmailClaim != null)
{
userEmail = userEmailClaim.Value;
}
return userEmail;
}
您可能想看一下我在GitHub创建的库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.