如果我从IdentityUser继承,如何获取当前用户ID?

问题描述 投票:0回答:2

我在IdentityUser中添加一些字段,如a

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()

但是它不起作用。

感谢您的帮助!

我在SQL上迁移后,在IdentityUser中添加了一些字段,例如公共类CustomUser:IdentityUser {public string field1 {get; set;} public string field2 {get; set;}}} [

在ASP.Net Core中,如果您的控制器继承了Microsoft.AspNetCore.Mvc.Controller,则可以从User属性中获取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;

您还可以从数据库的用户实体获取所有字段(包括ID)的数据:

1.DI UserManager

private readonly UserManager<ApplicationUser> _userManager; public HomeController(UserManager<ApplicationUser> userManager) { _userManager = userManager; }

2。使用如下所示:

var id = userManager.GetUserId(User); // get user Id
var user = await userManager.GetUserAsync(User); // get user's all data
    

您需要先在索赔中保存用户数据,然后获取授权的用户数据。
添加声明

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 asp.net-core asp.net-identity asp.net-core-identity
2个回答
1
投票

0
投票
添加声明
© www.soinside.com 2019 - 2024. All rights reserved.