I am doing an access management with a Roles, but when I do the foreach to save the role id I get the error 'The foreach instruction cannot work on variables of type "Rol" because "role" does not contain any definition of extension or instance public for "GetEnumerator"'
This is my Controller to login:
[HttpPost]
public async Task<IActionResult> Login(Usuarios _usuario)
{
Da_Logic _da_usuario = new Da_Logic();
var usuario = _da_usuario.EncontrarUsuarios(_usuario.user, _usuario.pass);
if (usuario != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.UserData, usuario.Usuario),
new Claim("Usuario", usuario.Usuario),
};
foreach (string rol in usuario.Rol)
{
claims.Add(new Claim(ClaimTypes.Role, rol));
}
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
This is the logic to find the user:
public Usuarios EncontrarUsuarios(string usuario, string password)
{
Usuarios obj = new Usuarios();
var cn = new Conexion();
//Conect BD
using (var conexion = new SqlConnection(cn.getcadenaSQL()))
{
string query = "SELECT * FROM user WHERE Usuario = @user AND Password = @password";
SqlCommand cmd = new SqlCommand(query, conexion);
cmd.Parameters.AddWithValue("user", user);
cmd.Parameters.AddWithValue("password", pass);
cmd.CommandType = CommandType.Text;
conexion.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
obj = new Usuarios()
{
Id_Usuario = Convert.ToInt32(dr["Id_Usuario"].ToString()),
Usuario = dr["Usuario"].ToString(),
Password = dr["Password"].ToString(),
Id_Rol = (Rol)dr["Id_Rol"],
};
}
}
}
return obj;
}
This is the role model
public enum Rol
{
Administrador = 1,
Empleado = 2,
}
and this is the User model
public class Usuarios
{
public int Id_Usuario { get; set; }
public string user { get; set; }
public string pass{ get; set; }
public Rol Id_Rol { get; set; }
}
I have already tried changing the foreach logic but I still get the error. It is the only error that marks me