簡體   English   中英

如果我從 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()

但它不起作用。

感謝幫助!

在 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;

您還可以從數據庫的 User 實體中獲取所有字段(包括 Id)的數據:

1.DI用戶管理器

    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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM