我只是ASP.NET MVC的初學者。我剛剛開始創建我的登錄頁面,但它工作正常,但當用戶輸入錯誤憑證時,我遇到了問題。這是我做了什麼:ASP.NET MVC:不顯示ModelState錯誤消息
用戶配置
public partial class UserProfile
{
public int UserId { get; set; }
[Display(Name = "User name")]
[Required(ErrorMessage = "Username is required.")]
public string UserName { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
public bool IsActive { get; set; }
}
的HomeController:
public class HomeController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserProfile objUser)
{
if (ModelState.IsValid)
{
using (DB_Entities db = new DB_Entities())
{
var obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserId.ToString();
Session["UserName"] = obj.UserName.ToString();
return RedirectToAction("UserDashBoard");
}
}
}
else
{
ModelState.AddModelError("", "Invalid Credentials");
}
return View(objUser);
}
public ActionResult UserDashBoard()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
}
而且查看
@model MyWebApplication.Models.UserProfile
@{
ViewBag.Title = "Login";
}
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Login" class="btn btn-default" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我不確定當用戶鍵入未存儲在數據庫中的用戶名時,爲什麼沒有顯示消息「無效憑證」。
它不顯示,因爲如果證書無效,程序的流程不會設置模型狀態錯誤。只有當'ModelState.IsValid'爲false時才設置錯誤。如果這是真的,那麼您正在對用戶進行身份驗證,但是如果無效則不會返回錯誤。 –
在任何情況下,您都不會將密碼作爲純文本存儲在數據庫中 - 您的散列(和鹽)。我強烈建議你的工作儘管[安全,認證和授權](https://www.asp.net/mvc/overview/security) –