How did you generate a valid token for postman?
ASP.NET Core Web API - Application returning null logged in user id
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:
** 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
1 answer
Sort by: Most helpful
-
Bruce (SqlWork.com) 81,981 Reputation points Volunteer Moderator
2021-12-03T16:05:13.203+00:00