Fri*_*rip 7 asp.net asp.net-identity asp.net-core asp.net-core-identity
我在 IdentityUser 中添加一些字段,例如
public class CustomUser: IdentityUser
{
public string field1 {get;set;}
public string field2 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
迁移后,在 Sql Management studio 上我拥有所有数据,我添加了.OnModelCreating
但是,我如何从当前授权的 CustomUser 中获取任何字段(如 ID)
我尝试使用
using Microsoft.AspNet.Identity;
CustomUser.Identity.GetUserId()
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
感谢帮助!
Xue*_*hen 12
在 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;
Run Code Online (Sandbox Code Playgroud)
您还可以从数据库的 User 实体中获取所有字段(包括 Id)的数据:
1.DI用户管理器
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
Run Code Online (Sandbox Code Playgroud)
2.使用方法如下:
var id = userManager.GetUserId(User); // get user Id
var user = await userManager.GetUserAsync(User); // get user's all data
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10702 次 |
最近记录: |