2017-03-05 34 views
3

在ASP.NET核心控制器中,我可以訪問User以獲取所有當前用戶聲明爲ClaimsPrincipal。現在我添加了一個新用戶,使用userManager.CreateAsync,添加了一些聲明,並且需要將他的所有聲明作爲ClaimsPrincipal用於其他一些功能。
我試過如下:從用戶管理器獲取ClaimsPrincipal

var user1 = new IdentityUserEntity 
    { 
// set username and stuff 
    }; 
    var result = await userManager.CreateAsync(user1, passwort); 
    await userManager.AddClaimAsync(user1, new System.Security.Claims.Claim(MyClaimTypes.Stuff, MyClaimValues.Whatever)); 

之後,我創建了一個ClaimsPrincipal這樣的:

var user1cp = new ClaimsPrincipal(new ClaimsIdentity(await userManager.GetClaimsAsync(user1))); 

問題是,這ClaimsPrincipal不包含的NameIdentifier(也許其他的東西?)。

如何從添加到數據庫的用戶添加一個完整的ClaimsPrincipal?

回答

2

我認爲你正在尋找CreateUserPrincipalAsync方法SignInManager

/// <summary> 
/// Creates a <see cref="ClaimsPrincipal"/> for the specified <paramref name="user"/>, as an asynchronous operation. 
/// </summary> 
/// <param name="user">The user to create a <see cref="ClaimsPrincipal"/> for.</param> 
/// <returns>The task object representing the asynchronous operation, containing the ClaimsPrincipal for the specified user.</returns> 
public virtual async Task<ClaimsPrincipal> CreateUserPrincipalAsync(TUser user) => await ClaimsFactory.CreateAsync(user);