1

I have a problem I'm stuck with that I do not know how to solve. I want to be able to display items associated with my logged in user on a view. I have previously done a many to many relationship between user and ticket. Now I want to make a UserProfile where I can show which Tickets are connected to the logged in user. But there is a problem when I do not know how to get urgent information about when you are logged in. I use MVC IdentityUser and Ef Core.

I have tried something in this direction

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);
}
RB.
  • 36,301
  • 12
  • 91
  • 131
Daniel
  • 369
  • 2
  • 4
  • 9
  • Does this answer your question? [ASP.NET Core Identity - get current user](https://stackoverflow.com/questions/38751616/asp-net-core-identity-get-current-user) – Christoph Lütjen Jul 28 '21 at 10:07

2 Answers2

1

I usually write an extension method to get the current user 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.");
        }
    }
}

So, you would do:

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);
    }
}
leotuna
  • 378
  • 3
  • 11
1

Try using this code

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

}
Wowo Ot
  • 1,362
  • 13
  • 21