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
User has only one role, that's why you can't iterate through it. It is an element not a list of elements.
In simple, your foreach is left over, you must change this
For this
The problem you have is that the user's role attribute can only have a role assigned to it, since it is not a list, it gives you the error, although it can be confusing, no enum is not a list that is made to be traversed so that it can be traversed, therefore, you can't get "roles" or string. If you want to iterate through all types of roles you can do:
The result would be:
The way you have it ready, it only supports one role assigned to the user class, so if you have to have more than one role, you would have to use a list of roles or an array and then go through the array