Asp.net mvc 如何避免在ASP.NET MVC 5中使用空密码字段登录?
我正在从事一个ASP.NETMVC5项目,在这个项目中我创建了一个自定义的登录和注册页面。应用程序运行良好,但问题是即使我的密码字段为空,我也可以登录 以下是控制器的代码(我正确使用了所有名称空间和引用) 我的观点是:Asp.net mvc 如何避免在ASP.NET MVC 5中使用空密码字段登录?,asp.net-mvc,entity-framework-4,html-helper,Asp.net Mvc,Entity Framework 4,Html Helper,我正在从事一个ASP.NETMVC5项目,在这个项目中我创建了一个自定义的登录和注册页面。应用程序运行良好,但问题是即使我的密码字段为空,我也可以登录 以下是控制器的代码(我正确使用了所有名称空间和引用) 我的观点是: @model MvcApplication2.Models.Register @{ ViewBag.Title = "LogIn"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>LogIn</
@model MvcApplication2.Models.Register
@{
ViewBag.Title = "LogIn";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>LogIn</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Register</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Email_Id)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email_Id)
@Html.ValidationMessageFor(model => model.Email_Id)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="LogIn" />
</p>
</fieldset>
}
< div>
@Html.ActionLink("Register Now", "Register")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@model mvcapapplication2.Models.Register
@{
ViewBag.Title=“登录”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
登录
@使用(Html.BeginForm()){
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
登记
@LabelFor(model=>model.Email\u Id)
@EditorFor(model=>model.Email\u Id)
@Html.ValidationMessageFor(model=>model.Email\u Id)
@LabelFor(model=>model.Password)
@EditorFor(model=>model.Password)
@Html.ValidationMessageFor(model=>model.Password)
}
@ActionLink(“立即注册”、“注册”)
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
}
将此检查添加到您的IsValid
方法中:
private bool IsValid(string email, string password)
{
if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
return false;
//... etc.
private bool有效(字符串电子邮件、字符串密码)
{
if(string.IsNullOrWhiteSpace(password)| | password.Length<6)
返回false;
//……等等。
问题是,因为您没有使用ModelState.IsValid
,所以您需要一个替代方法。您的IsValid
方法似乎就是这个替代方法。只需将[Required]
属性添加到您的Password
属性中就可以了。是的,我已经添加了[Required]仍然不能正常工作。什么不能正常工作?如果您添加了该属性,您甚至无法提交表单,ModelState
将无效,即使您禁用客户端验证,您也无法保存它(使用If(ModelState.IsValid)
。如果没有,则返回视图)问题是,它正在检查电子邮件id,但如果您将密码字段留空并提交表单,它将允许这样做。如果电子邮件和密码都为空,则它将显示为必填项,但允许用户在系统中输入。我认为IsValid方法没有正确检查密码条件。没有ots。请阅读我之前的内容注释。如果使用if(ModelState.IsValid)
,如果不是,则返回视图(不保存数据)。ModelState
将无效,如果您具有[必需]
属性并且发布空值。请使用框架的功能,而不是IsValid
方法!
private bool IsValid(string email, string password)
{
if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
return false;
//... etc.