0

I have some Web API endpoints that need the current user Id to link some data with the user making the request.

At this time I'm doing this in every Action to get the current user id:

string userName = User.Identity.Name;
var user = await _userManager.FindByNameAsync(userName);

This FindByNameAsync really annoys me. I expected the User id to be included in the User.Identity information, avoiding me to do this FindByNameAsync call in every action (Isn't the id more important than the name?). I haven't profiled this yet but it seems a bit waste of time to do this when such an important piece of information should be included in the User.Identity.

Is there any way to get the user id in a faster way? By faster I mean more performant.

Notbad
  • 5,936
  • 12
  • 54
  • 100
  • 1
    https://stackoverflow.com/questions/46112258/how-do-i-get-current-user-in-net-core-web-api-from-jwt-token this might help – Kevin Feb 18 '20 at 12:11
  • 1
    Make sure you've passed a claim of user id when building the Token. After that you can get the user id via Claim. – itminus Feb 19 '20 at 02:08
  • Thanks for the point. Just did it yesterday. Did not notice I could add a claim for this :) – Notbad Feb 19 '20 at 09:03

0 Answers0