ASP.NET Core Web API - Application returning null logged in user id

MICHAEL 1 Reputation point
2021-12-03T13:54:22.183+00:00

In ASP.NET Web API, I have a model called Student and also ApplicationUser from IdentityDbContext.

The Student Model has a field called UserId which is a foreign key of Id from ApplicationUser.

public class StudentService : IStudentService  
{  
    public async Task<IEnumerable<StudentGetProfileDto>> GetStudentProfile()  
    {  
        var mapper = new EntityMapper();  
        var userId = _httpContextAccessor.HttpContext.User.GetLoggedInUserId<long>();  
        var studentProfile = await _unitOfWork.StudentRepository.GetAll();       
        var studentDtoProfile = studentProfile.Where(x => x.UserId == userId).Select(c => mapper.FromStudentProfileToStudentGetDto(c)).ToList();  

        return studentDtoProfile;  
    }  
}  

I am trying to test using POSTMAN. When I put the bearer token and send the Get Request The output is null.

Also I changed the var userId to:

          var userId = Int64.Parse(_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));  

and

         var principal = new ClaimsPrincipal();  
         var userId = Convert.ToInt64(principal.FindFirstValue(ClaimTypes.NameIdentifier));  

The same thing still happen:

154804-null-loggedinuserid.png

** But when I changed var userId (var userId=2) to the id of the user with the token. For instance 2. I got data on postman.**

Why is it not getting the logged in Id?

What can I do to resolve this?

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 81,981 Reputation points Volunteer Moderator
    2021-12-03T16:05:13.203+00:00

    How did you generate a valid token for postman?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.