2
我一直在尋找並試圖解決我現在遇到的問題。我是一個用戶模型,我想使用沒有看到任何錯誤定製authentication.I'm驗證的用戶,同時提交form.But我可以看到在輸出異常window.Here是我的模型類:未知模塊-mvc自定義身份驗證發生第一次機會例外類型'System.NullReferenceException'
public class UserInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required(ErrorMessage="User Name is required")]
[Display(Name="User Name")]
[MaxLength(20, ErrorMessage = "The Maximum length allowed is 20 characters")]
[MinLength(4, ErrorMessage = "The Minimum length is 3 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Enter a proper email address")]
[MaxLength(30, ErrorMessage = "Maximum length allowed for an email is 30 characters")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Pass { get; set; }
[Required(ErrorMessage = "Confirm your password")]
[Display(Name = "Confirm Password")]
[Compare("Pass", ErrorMessage = "Passwords should match")]
[DataType(DataType.Password)]
[NotMapped]
public string Confirm { get; set; }
}
這裏是我的登錄操作方法在我的控制器中:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserInfo user)
{
if (ModelState.IsValid)
{
string EncryptPass;
EncryptPass = Crypto.SHA256(user.Pass);
Console.WriteLine(EncryptPass);
var i = db.Database.ExecuteSqlCommand("select count(*)
from userinfos where username = {0}", user.Name);
if (i > 0)
{
var j = db.Database.ExecuteSqlCommand("select
count(*) from userinfos where pass = {0}", EncryptPass);
if (j > 0)
{
Session["User"] = user.Name;
FormsAuthentication.SetAuthCookie(user.Name,
false);
RedirectToAction("Create", "Ministry");
}
else
{
RedirectToAction("Login");
ModelState.AddModelError(user.Pass, "Password is
incorrect");
}
}
else
{
RedirectToAction("Login");
ModelState.AddModelError(user.Name, "Our records
shows
that no account exists on your name");
}
}
return View();
}
我的看法是:
@model ChurchWebsite.Models.UserInfo
@{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Login</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Pass)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Pass)
@Html.ValidationMessageFor(model => model.Pass)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
哪一行會引發錯誤?由於你的'[Compare(「Pass」,ErrorMessage =「Passwords should match」)]''ModelState'將始終無效。調用'RedirectToAction();'後,添加'ModelState'錯誤有什麼意義? –
我應該考慮爲登錄創建單獨的控制器並在該控制器中編寫用於登錄的ActionMethod? –