I have this code in ASP.NET Core Web API:
DTO:
public class AuthRequest
{
public string Email { get; set; }
public string Password { get; set; }
}
public class AuthResponse
{
public string Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Token { get; set; }
}
Services:
public interface IAuthService
{
Task<AuthResponse> Login(AuthRequest request);
}
public async Task<AuthResponse> Login(AuthRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
{
throw new Exception($"User with {request.Email} not found.");
}
var result = await _signInManager.PasswordSignInAsync(user.UserName, request.Password, false, lockoutOnFailure: false);
if (!result.Succeeded)
{
throw new Exception($"Credentials for '{request.Email} aren't valid'.");
}
JwtSecurityToken jwtSecurityToken = await GenerateToken(user);
var roles = await _userManager.GetRolesAsync(user);
AuthResponse response = new AuthResponse
{
Id = user.Id,
Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
Email = user.Email,
UserName = user.UserName,
roles,
};
return response;
}
From the code above, I want to include roles of the logged in user in the AuthResponse. So I added, roles
But I got this error:
Error CS0747 Invalid initializer member declarator
roles is highlighted.
How do I resolve this?
Thanks