我正在创建一个必须使用MVC模式完成的学校应用程序。首先,我试图获得一个简单的注册和登录页面,就像我可以在我的数据库中存储和检索一样,然后应用程序的其余部分应该相当简单。我使用我的大学的SQL服务器为我的数据库和使用ADO.NET实体数据模型(第一次)。
我正在使用在线教程来帮助我,这一切似乎都运行良好,但现在的麻烦是,当我尝试使用我的表中已有的详细信息登录时,我得到了一个'Http 401.0 - Unauthorized'页面。
我知道我在电子邮件中输入的内容密码框与我使用标签测试时从数据库中检索的内容相匹配,它们都匹配。如果有帮助,我正在使用ASP.NET 4.5.2。
我的桌子很简单 -
Email (pk)(varchar) - For logon
Password (varchar) - For logon
First_Name (varchar)
我的代码如下;
UserLogon View -
public class UserLogon
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
用户管理器视图 -
public class UserManager
{
private ac9555fEntities dre = new ac9555fEntities();
public string GetUserPassword(string userEmail)
{
var user = from o in dre.UserTables where o.Email == userEmail select o;
if (user.ToList().Count > 0)
return user.First().Password;
else
return string.Empty;
}
}
帐户控制器 -
public class AccountController : Controller
{
public ActionResult LogOn()
{
return View();
}
//
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(UserLogon model, string returnUrl)
{
if (ModelState.IsValid)
{
UserManager userManager = new UserManager();
string password = userManager.GetUserPassword(model.Email);
if (string.IsNullOrEmpty(password))
{
ModelState.AddModelError("", "The user login or password provided is incorrect.");
}
if (password == model.Password)
{
FormsAuthentication.SetAuthCookie(model.Email, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Welcome", "Home");
}
}
else
{
ModelState.AddModelError("", "The password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
家庭控制器 -
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult Welcome()
{
return View();
}
登录视图 -
@model WebApplication5.Models.ViewModels.UserLogon
....
@using (Html.BeginForm())
{
....
@Html.EditorFor(model => model.Email)
....
@Html.EditorFor(model => model.Password)
....
<input type="submit" value="Log On" />
}
如果我包含太多/不够的代码,我很抱歉,这是我第一次使用MVC / ADO.NET实体数据模型。通过查看此处和网络上其他地方的其他内容,我觉得有一个额外的授权层不需要,但我尝试的任何解决方案都无法正常工作。谁能发现我的代码存在缺陷?
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
答案 0 :(得分:1)
发生错误是因为您的weg.config
文件未指定使用表单身份验证。修改<system.web>
部分以包含
<system.web>
....
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="10" /> // adjust as required
</authentication>
</system.web>
但是您的代码存在许多其他问题。
ModelState.AddModelError(..)
代码应该相同
到第一个(从不透露这两个值中的哪一个是不正确的)if(Url.IsLocalUrl(returnUrl) && ...
代码做什么,但一旦您进行身份验证
用户,它应该是if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Welcome", "Home"); }
我建议您完成Security, Authentication and Authorization上的基本教程,并使用MVC和Identity的内置功能来正确处理所有这些。