Asp.Net Core 2.0 如何在不使用声明的情况下获取有关登录用户的信息

How to get information about the logged user without using claims in Asp.Net Core 2.0

我需要当前登录用户的角色和电子邮件等信息,但由于有关帐户的详细信息在登录时可能会发生变化,因此我被告知不要使用声明。所以基本上每次我需要有关用户的信息时,我都需要在数据库中进行搜索。我怎么能实现这样的事情?我考虑过将 ID 存储在某处并根据它查找信息,但我认为有一些 'cooler' 方法。

使用User属性的页面。它有一个名为 Identity 的内部属性,其中包含当前登录人员的用户名。还有一个名为 GetUserId() 的扩展方法可以帮助您找到当前登录用户的用户 ID。 有了用户id,就可以查询数据库,找到用户的更多信息。

考虑以下可以简化提取当前用户 ID 的代码:

public static string ValidateAndGetUserId(IIdentity identity)
{
    if (identity == null)
        throw new ApplicationException("No User is logged in");

    var userId = identity.GetUserId();

    if (string.IsNullOrWhiteSpace(userId))
        throw new ApplicationException("No User is logged in");

    return userId;
}

您可以使用声明来获取有关用户的信息,即使该信息可能会在以后更新。

您所要做的就是:在您保存用户的更新信息后,您只需重新登录他们,索赔就会更新为新信息。

例如:

  1. 用户访问 "my account" 页面。

  2. 用户修改了他们的信息,然后点击保存按钮。

  3. 在您的控制器中,保存用户信息后,您只需再次登录即可。

这是我目前正在开发的 MVC 5 应用程序的示例,但这个想法应该仍然适用于 asp.net 核心:

    // POST: MyAccount
    [Authorize(Roles = "Admin,Host,User")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> MyAccount([Bind(Include = "FirstName,LastName,Email,Phone,Country,State,TimeZone")] MyAccountVM vm)
    {

        var id = User.Identity.GetUserId();

        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByIdAsync(id);

            if (user == null)
            {
                return HttpNotFound();
            }

            user.FirstName = vm.FirstName;
            user.LastName = vm.LastName;
            user.Email = vm.Email;
            user.UserName = vm.Email;
            user.Phone = vm.Phone;
            user.Country = vm.Country;
            user.State = vm.State;
            user.TimeZone = vm.TimeZone;

            var result = await UserManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                var currentUser = await UserManager.FindByIdAsync(user.Id);

                if (currentUser != null)
                {
                   await SignInManager.SignInAsync(currentUser, isPersistent: false, rememberBrowser: false);
                }

                TempData["saved"] = "true";

                return RedirectToAction("MyAccount");
            }
        }
        return View();
    }