我有这个LoginController
。LoginModel
能够提供对字符串长度和必填字段的验证。这在剃刀页面中显示得很好。
public class LoginController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(LoginModel model)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.Username, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Username, model.NotPublicPc);
var url = FormsAuthentication.GetRedirectUrl(model.Username, model.NotPublicPc);
return Redirect(url);
}
else
{
//here I want to throw my own validation message or otherwise
//give feedback that the login was unsuccessful
}
}
return View();
}
}
public class LoginModel
{
[Required]
[StringLength(50, MinimumLength = 4)]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Display(Name = "Keep me logged in - do not check on public computer")]
public bool NotPublicPc { get; set; }
}
如何抛出我自己的验证错误 - 即我想在登录失败时显示一条消息。虽然我现在很欣赏在浏览器中完成所需和长度的验证,但这是不同的。
我试过投掷Exception
和System.ComponentModel.DataAnnotations.ValidationException