显示错误密码的错误消息

时间:2017-10-03 02:30:49

标签: asp.net

我有这个登录代码,我想显示(错误消息“无效的用户和密码”)如果有人输入了错误的密码,目前我的代码只是在发生错误时重定向到同一页面。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(Login l,string ReturnUrl="")
    {
        using (graceEntities dc = new graceEntities())
        {
            var user = dc.tbl_User.Where(a => a.UserName.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(user.UserName,l.RememberMe);
                if (Url.IsLocalUrl(ReturnUrl))
                {
                    return Redirect(ReturnUrl);
                }
                else
                {
                    return RedirectToAction("Index","Main");
                }
            }


        }


        ModelState.Remove("Pasword");
            return View();
    }

1 个答案:

答案 0 :(得分:0)

您需要处理在数据库中找不到用户的情况。请阅读以下代码中的内容注释以获得进一步说明:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login model, string ReturnUrl = "")
{
    // 1. Do validation and return view if validation errors
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // 2. No validation error so search db for user 
    using (graceEntities dc = new graceEntities())
    {
        var user = dc.tbl_User
            .Where(a => a.UserName.Equals(model.Username) &&
            a.Password.Equals(model.Password)).FirstOrDefault();
        if (user != null)
        {
            FormsAuthentication.SetAuthCookie(user.UserName, model.RememberMe);
            if (Url.IsLocalUrl(ReturnUrl))
            {
                return Redirect(ReturnUrl);
            }

            // No return url, redirect to main/index
            return RedirectToAction("Index", "Main");
        }
    }


    // 3. We made it here, so user was not found
    ModelState.AddModelError("", "Invalid login attempt.");
    return View(model);
}