如果我继承自 IdentityUser,如何获取当前用户 ID?
How to get current user id, if i inherits from IdentityUser?
我在 IdentityUser 中添加了一些字段,例如
public class CustomUser: IdentityUser
{
public string field1 {get;set;}
public string field2 {get;set;}
}
迁移后,在 Sql Management Studio 上,我拥有所有数据,我添加了 .OnModelCreating
但是,我如何从当前授权的 CustomUser 中获取任何字段(如 ID)
我试试用
using Microsoft.AspNet.Identity;
CustomUser.Identity.GetUserId()
但是没用。
感谢帮助!
您需要先在声明中保存用户数据,然后再获取授权用户数据。
添加声明
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
获得索赔
var userId = (HttpContext.Current.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)
在 ASP.Net Core 中,如果您的控制器继承了 Microsoft.AspNetCore.Mvc.Controller
,您可以从用户 属性 获得 IClaimsPrincipal
并获得实际的 "Id"的用户,
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
您还可以从数据库的User实体中获取所有字段(包括Id)的数据:
1.DI 用户管理器
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
2.Use 如下所示:
var id = userManager.GetUserId(User); // get user Id
var user = await userManager.GetUserAsync(User); // get user's all data
我在 IdentityUser 中添加了一些字段,例如
public class CustomUser: IdentityUser
{
public string field1 {get;set;}
public string field2 {get;set;}
}
迁移后,在 Sql Management Studio 上,我拥有所有数据,我添加了 .OnModelCreating
但是,我如何从当前授权的 CustomUser 中获取任何字段(如 ID)
我试试用
using Microsoft.AspNet.Identity;
CustomUser.Identity.GetUserId()
但是没用。
感谢帮助!
您需要先在声明中保存用户数据,然后再获取授权用户数据。
添加声明
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
获得索赔
var userId = (HttpContext.Current.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)
在 ASP.Net Core 中,如果您的控制器继承了 Microsoft.AspNetCore.Mvc.Controller
,您可以从用户 属性 获得 IClaimsPrincipal
并获得实际的 "Id"的用户,
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
您还可以从数据库的User实体中获取所有字段(包括Id)的数据:
1.DI 用户管理器
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
2.Use 如下所示:
var id = userManager.GetUserId(User); // get user Id
var user = await userManager.GetUserAsync(User); // get user's all data