外部登录后从数据库获取AspNetUsers(CurrentUser)

时间:2016-11-02 19:47:34

标签: c# asp.net-core-mvc

我正在尝试使用OpenID登录后获得一个Steam用户头像。 但我不知道如何在登录后立即检索数据库用户(手动将avater添加到数据库中)

我将新属性添加到应用程序用户:

// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
    public string AvatarPath { get; set; }
}

我创建了一个新的迁移并更新了数据库。我正在尝试在登录后立即更改用户的数据,但如何检索当前用户?!

的AccountController:

// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
    //Get Steam User
    if(info.LoginProvider.ToLower() == "steam")
    {
        //I need the DB User

    }

    _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
    return RedirectToLocal(returnUrl);
}

我试过了:

ApplicationUser u = await GetCurrentUserAsync();

你是空的

1 个答案:

答案 0 :(得分:2)

找到解决方案:

var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
    //Get Steam User
    if(info.LoginProvider.ToLower() == "steam")
    {
        var user = await _userManager.FindByLoginAsync("Steam", info.ProviderKey);
        user.AvatarPath = SteamApi.GetSteamAvatar(playerData);
        var ir = await _userManager.UpdateAsync(user);
        if(!ir.Succeeded)
        {
            foreach (var err in ir.Errors)
            {
                Console.WriteLine(err.Code + " - " + err.Description);
            }
        }
    }
}

要修复包含UTF字符的Steam用户的错误,请参阅: .NET MVC 6 / vNext UserValidator to allow alphanumeric characters 设置AllowedUserNameCharactersstring.empty会跳过用户名验证。

唯一的问题是,UserManager不会更新内存中的数据,重定向到我的HomeController仍会显示旧数据......但数据库已正确更新