0

I'm trying to get current authenticated UserId, but the returned value in the browser console is always "null". (ASP Web API with Angular).

*NOTE: There is NO problem in Registration/Login & NO errors at client-side, everything is working well, but I can NOT get user claims.

ASP Web API controller code (AccountController.cs) :

[HttpGet]
[Route("api/User/get-player-id")]
public ApplicationUser PlayerID()
{
    string currentUserId = User.Identity.GetUserId();
    ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
    return currentUser;`

Angular service code (api.service.ts)

getCurrentUser(){
   return this.http.get(`http://localhost:51075/api/User/get-player-id`);
}

home.component.ts:

ngOnInit() {
    this.apiService.getCurrentUser().subscribe(res=> {
     this.userID = res; console.log(this.userID); 
    });
}
Topher
  • 1,011
  • 11
  • 19
  • 1
    Could you post the contents of ApplicationUser? – elvirus Mar 13 '19 at 15:35
  • And also: Did you debug the controller? What values are in currentUserId and currentUser before the controller returns currentUser? – elvirus Mar 13 '19 at 15:41
  • Here is: https://pastebin.com/mkamCgBN – Hossam Brgoth Mar 13 '19 at 15:44
  • *NOTE: I followed this 3 tutorials series literally for making registration system, however, I don't know why can't get user claims: http://www.codaffection.com/angular-5-tutorial/angular-5-user-registration-web-api/ – Hossam Brgoth Mar 13 '19 at 15:48
  • Controller debugging results: https://i.imgur.com/GrLPemS.png – Hossam Brgoth Mar 13 '19 at 20:53
  • So it seems that the current user is actually not logged in. The code after User.Identity.GetUserId() seems ok, but if currentUserId is already null you will not get any further. I really cannot point you in the right direction without more knowledge of your code. Maybe the cookie settings are odd or the login itself has some problem. – elvirus Mar 14 '19 at 17:56
  • Please try adding [Authorize] right above your controller method and put a breakpoint in your controller code. Let me know if the breakpoint will be hit or not. – elvirus Mar 14 '19 at 17:58
  • Does this help you? https://stackoverflow.com/questions/35577280/how-to-get-current-userid-in-identity-3-0-user-getuserid-returns-null/35683419 – elvirus Mar 14 '19 at 18:01

0 Answers0