0

I'm trying to get the current user id logged in so I can pull details down for this user as well assign details to the user e.g. booking events, seeing events they have booked, etc.

I have been trying to do like this

var USERID = User.Claims.FirstOrDefault(c => c.Type == "Id")

but I get an error when trying to assign to int.

I have my service method within my data project connecting to db then I pass these methods from the service into the controller, if that helps at all.

Any help would be great.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
pabs095
  • 33
  • 4
  • "I get an error..." What is the error then? It **never** helps to say "I have an error". Error messages are there for a reason. – Mohammad Dehghan Apr 13 '20 at 07:58
  • "Cannot implicitly convert type "System.Security.Claims.Claim" to "int" – pabs095 Apr 13 '20 at 08:03
  • 1
    See here: [How to get the current logged in user Id in ASP.NET Core](https://stackoverflow.com/questions/30701006/how-to-get-the-current-logged-in-user-id-in-asp-net-core). Or: `var userId = Int.Parse(User.Claims.FirstOrDefault(c => c.Type == "Id").Value);`? I'm not sure if `c.Type == "Id"` is correct. – Mohammad Dehghan Apr 13 '20 at 08:08
  • Maybe it helps you. follow this link : https://stackoverflow.com/questions/51765214/get-user-id-in-asp-net-core-2 – ssmmoo Apr 13 '20 at 12:08

2 Answers2

0

The correct way to do this is via User.FindFirstValue(ClaimTypes.NameIdentifier).

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

You can use the IHttpContextAccessor to access to HttpContext and get Current UserId like this

public int GetCurrentUserId()
{
    var claimsIdentity = _contextAccessor.HttpContext.User.Identity as ClaimsIdentity;
    var userDataClaim = claimsIdentity?.FindFirst("Id");//or claimsIdentity?.FindFirst(ClaimTypes.NameIdentifier);
    var userId = userDataClaim?.Value;
    return string.IsNullOrWhiteSpace(userId) ? 0 : int.Parse(userId);
}

Or

int userId = Convert.ToInt32((User.Identity as ClaimsIdentity).FindFirst(ClaimTypes.Name).Value);
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41