Send error for duplicate login C#

Asked

Viewed 103 times

0

I’m implementing a login system, but I can’t send an error message to when I try to create a duplicate login. I declared the login as follows:

[Index("User_UserName_Index", IsUnique = true)]
public string Login { get; set; }

But I can’t return an error by saying that the login already exists

I thought I’d use a try, but I don’t know how I could do it.

For login verification I did as follows

public class LoginController : Controller
{

    Contexto db = new Contexto();
    // GET: Login
    public ActionResult Index()
    {
        if (TempData["ViewData"] != null) 
        {
            ViewData = (ViewDataDictionary)TempData["ViewData"];
        }
        return View();
    }

    public ActionResult Autenticar(string login, string senha)
    {

        try
        {
            var usuario = db.Usuarios.FirstOrDefault(p => p.Login == login && p.Senha == senha);

            if (usuario.Admim == true)
            {
                Session["admLogado"] = usuario;
                return RedirectToAction("Index", "Usuarios");
            }
            else
            {
                Session["usuarioLogado"] = usuario;
                return RedirectToAction("Login", "Home");
            }
        }
        catch(Exception ex)
        {
            ModelState.AddModelError(string.Empty, "Usuario ou senha invalidos");
            TempData["ViewData"] = ViewData;
            return RedirectToAction("Index");
        }


    }
  • Why would Login be duplicated? It does not validate if there is already a user with the same data at the time of registration?

3 answers

0

Friend with Try-catch you will not be able to validate that the login already exists.
Behold:

Firstordefault(Ienumerable)

Returns the first element of a sequence or a default value if a sequence contains no elements

That is, it does not launch an exeception if the value is not in the collection, so it will not fall in your catch.
For this you can use the function First() in place of FirstOrDefault(), This yes launches exeception. See these links to learn more about the functions Firstordefault and First

0

Whenever you seek some user information and do not find it, would fall into the catch when trying to access "Admin", returning a NullPointer.

Try it like this:

public ActionResult Autenticar(string login, string senha)
{
	var usuario = db.Usuarios.FirstOrDefault(p => p.Login == login && p.Senha == senha);

	if (usuario != null)
	{
		if (usuario.Admim)
		{
			Session["admLogado"] = usuario;
			return RedirectToAction("Index", "Usuarios");
		}
		else
		{
			Session["usuarioLogado"] = usuario;
			return RedirectToAction("Login", "Home");
		}
	}
	else
	{
		ModelState.AddModelError(string.Empty, "Usuario ou senha invalidos");
		TempData["ViewData"] = ViewData;
		return RedirectToAction("Index");
	}
}

0

public ActionResult Autenticar(string login, string senha)
{

    try
    {
        var usuarios = db.Usuarios.Where(p => p.Login == login && p.Senha == senha);

      if(usuarios.Count==0)
      {
         ModelState.AddModelError(string.Empty, "Usuario ou senha invalidos");
         TempData["ViewData"] = ViewData;
         return RedirectToAction("Index"); 
      }
     else if(usuarios.Count==1)
     {
        var usuario=usuarios.First(); 
        if (usuario.Admim == true)
        {
            Session["admLogado"] = usuario;
            return RedirectToAction("Index", "Usuarios");
        }
        else
        {
            Session["usuarioLogado"] = usuario;
            return RedirectToAction("Login", "Home");
        }
      }
    else
    {
      //Login Duplicado
    }


    }
    catch(Exception ex)
    {
        //Erro inesperado
    }

}

I believe this works, but I think you should check the duplicate login when making the registration.

Exception does not serve for these types of treatment as a message from: invalid user or password, if an exception occurs any message will always be the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.