У меня проблема в CreateAsync.
Я использую .NET 8.0.
Код: Выделить всё
public async Task CreateAsync(ArticleDto dto, ClaimsPrincipal userPrincipal)
{
var userId = userPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
throw new KeyNotFoundException("UserId not found");
}
var user = await _dataContext.Users.FindAsync(userId);
if (user == null)
{
throw new KeyNotFoundException("User not found");
}
var category = await _dataContext.Categories.FindAsync(dto.CategoryId);
if (category == null)
{
throw new KeyNotFoundException("Category not found");
}
var article = new Article
{
Title = dto.Title,
Content = dto.Content,
Category = category,
User = user
};
_dataContext.Add(article);
await _dataContext.SaveChangesAsync();
return article;
}
Вот мой метод входа в систему:
Код: Выделить всё
public async Task LoginAsync(LoginDto loginDto)
{
var user = await dataContext.Users
.Include(u => u.Roles)
.FirstOrDefaultAsync( u => u.Email == loginDto.Email);
if (user == null || !VerifyPassword(loginDto.Password, user.Password))
{
throw new UnauthorizedAccessException("Credentials not valid" );
}
var claims = new List
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Email, user!.Email),
new Claim(JwtRegisteredClaimNames.Sub, user!.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
user.Roles.ForEach(r => claims.Add(new Claim(ClaimTypes.Role, r.Name)));
var k = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(key));
var signed = new SigningCredentials(k, SecurityAlgorithms.HmacSha256);
var expiration = DateTime.Now.AddMinutes(60);
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: expiration,
signingCredentials: signed
);
return new LoginResponse
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Email = user.Email,
TokenExpiration = expiration,
UserId = user.Id
};
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -8-web-api
Мобильная версия