I am currently working on the functionality of user liking items in the store. My goal is to allow a user to like a product and add it to the list of liked products, one user can like multiple products, and each product can be liked by multiple users. However, the problem is that when I test the request in Postman I get a 500 Internal server error - "System.FormatException: Input string was not in a correct format". The problem is that the value of the string variable cannot be converted to an integer in the ClaimsPrinciple class, althought I think I am doing it correctly? I did some coding and debugging. Do I need to return something in the controller? User is logged in but I get userId = 0 and product null however there are user and product with such Id in the database. I am so confused. Any suggestion's how to overcome that?
//Here are product and user entity
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public User User { get; set; }
[ForeignKey("UserId")]
public int UserId { get; set; }
}
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public List<Product> Products { get; set; }
public List<Product> LikedProducts { get; set; } = new List<Product>();
}
public static class ClaimPrincipleExtensions
{
public static string GetUsername(this ClaimsPrincipal user)
{
return user.FindFirst(ClaimTypes.Name)?.Value;
}
public static int GetUserId(this ClaimsPrincipal user)
{
return int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value); // Im getting an exception here
}
}
// Here is my controller
[HttpPost("add-to-favorites/{productId}")]
public async Task<ActionResult> AddToFavorites(int productId)
{
var userId = User.GetUserId();
var product = await _productRepository.GetProductById(productId);
var user = await _userRepository.GetUser(userId);
if (product == null)
{
return NotFound();
}
if (product.UserId == userId)
{
return BadRequest("You cannot like your own product.");
}
user.LikedProducts.Add(product);
await _context.SaveChangesAsync();
return Ok();
}


int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value);Seems, like at least one user has aValueforClaimTypes.NameIdentifierthat cannot be parsed to an int ... Separate this in two stepsvar val = user.FindFirst(ClaimTypes.NameIdentifier)?.Value; return int.Parse(val);and set a breakpoint at the second. So you'll see, whatvalactually is"saymon"into an int? You are probably querying the wrong property ...