繁体   English   中英

如何获取与登录用户相关的信息?

[英]How do I get information associated with a logged in user?

我有一个问题,我不知道如何解决。 我希望能够在视图上显示与我的登录用户关联的项目。 我之前做过 user 和 ticket 之间的多对多关系。 现在我想创建一个 UserProfile,我可以在其中显示哪些票证已连接到登录用户。 但是当我不知道如何获取有关您何时登录的紧急信息时出现问题。我使用 MVC IdentityUser 和 Ef Core。

我在这个方向上尝试了一些东西

public IActionResult MyProfile(string id)
{
    var Tickets = _db.UserTickets
          .Include(n => n.ApplicationUser)
          .Include(n => n.Ticket)
          .Where(n => n.UserId == id)
          .ToList();

    return View(Tickets);
}

我通常会编写一个扩展方法来获取当前用户 ID。

public static class ControllerExtensions
{
    public static string GetCurrentUserId(this ControllerBase controller)
    {
        try
        {
            var userId = controller.User.FindFirstValue(ClaimTypes.NameIdentifier);
            return userId;
        }
        catch
        {
            throw new Exception("Cannot find user id.");
        }
    }
}

所以,你会这样做:

public class YourController : Controller
{
    public IActionResult MyProfile()
    {
        var currentUserId = this.GetCurrentUserId();

        var Tickets = _db.UserTickets
            .Include(n => n.ApplicationUser)
            .Include(n => n.Ticket)
            .Where(n => n.UserId == currentUserId)
            .ToList();
    
        return View(Tickets);
    }
}

尝试使用此代码

public async Task getNumberFromUser()
{
    ClaimsPrincipal currentUser = this.User;
    var currentUserName = currentUser.Identity.Name.ToString();
    ApplicationUser user = await userManager.FindByNameAsync(currentUserName);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM