简体   繁体   English

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

[英]How to get current user id, if i inherits from IdentityUser?

I add some fields in IdentityUser like a我在 IdentityUser 中添加了一些字段,例如

public class CustomUser: IdentityUser
    {
        public string field1 {get;set;}
        public string field2 {get;set;}
    }

after migration, on Sql Management studio i had all data, which i added with .OnModelCreating迁移后,在 Sql Management Studio 上,我拥有所有数据,我使用.OnModelCreating添加了这些数据

But, How i can get any field from current authorized CustomUser (like a ID)但是,我如何从当前授权的 CustomUser 获取任何字段(如 ID)

I try use我尝试使用

using Microsoft.AspNet.Identity;

CustomUser.Identity.GetUserId()

But it doesnt work.但它不起作用。

Thanks for help!感谢帮助!

In ASP.Net Core,if your Controller inherits the Microsoft.AspNetCore.Mvc.Controller , you could get the IClaimsPrincipal from the User property and get the actual "Id" of the user,在 ASP.Net Core 中,如果您的 Controller 继承了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;

You can also get the data of all fields(include Id) from the database's User entity:您还可以从数据库的 User 实体中获取所有字段(包括 Id)的数据:

1.DI UserManager 1.DI用户管理器

    private readonly UserManager<ApplicationUser> _userManager;

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

2.Use it like below: 2.使用如下:

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

You need to first save user data in claims and then get authorized user data.您需要先将用户数据保存在索赔中,然后再获取授权用户数据。

Add Claims添加声明

var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

Get Claims获得索赔

var userId = (HttpContext.Current.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM