Asp.net
如何從 ASP.net 中的主體獲取電子郵件地址?
我正在嘗試獲取與目前使用者關聯的電子郵件。以下顯示了我在身份驗證中添加聲明的幾行。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); try { CreateDataConnection(); R_AuthenticateUser oAuthUser = oDataConnection.Authenticate(context.UserName,context.Password); string DB_User_roles = oAuthUser.UserLoginRoles; if (oAuthUser.Authenticated) { string[] aray = DB_User_roles.Split(','); identity.AddClaim(new Claim(ClaimTypes.Name, oAuthUser.UserID.ToString())); // keeps the login_ID identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName)); foreach (var item in aray) { // identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, item)); identity.AddClaim(new Claim(ClaimTypes.Role, item)); } context.Validated(identity); } else //if (context.UserName == "user" && context.Password == "user") { context.SetError("Incorrect credntials", "Provided Username and Password is incorrect"); return; } } catch (Exception ex) { int y = 0; } }目前在我的控制器中,我讀取了與使用者關聯的使用者 ID,如下所示?
[HttpGet] [PGAuthorization(Roles = "USER")] [Route("api/Address/GetAllAddresses")] public string GetAllAddressesByUser() { CreateDataConnection(); Int64 UserID = Convert.ToInt64((User as ClaimsPrincipal).Identity.Name); List<R_CustomerAddress> oUser = oDataConnection.GetAllAddressesByUser(UserID); string output = JsonConvert.SerializeObject(oUser); return output; }但是現在我需要使用我在身份驗證中添加的電子郵件來獲取使用者 ID。我嘗試使用
Int64 UserID = Convert.ToInt64((User as ClaimsPrincipal).Identity.Email);但它不起作用。有人可以幫我嗎?
如果您在身份驗證期間在聲明中添加電子郵件,您可以通過以下方式獲取它:
string email = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value
越短越好:
string email = this.user.FindFirstValue(ClaimTypes.Email);