我创建了一个必须使用MVC模式完成的学校应用程序。首先,我试图获得一个简单的注册和登录页面,并运行,就好像我可以在我的数据库中存储和检索一样,然后应用程序的其余部分应该相当简单。我正在使用我的大学的SQL服务器作为我的数据库并使用ADO.NET实体数据模型(第一次)。ASP.NET MVC简单的登录页面,用户名和密码匹配,但获取未经授权的消息
我正在使用一个在线教程来帮助我,它似乎工作得不错,但现在的麻烦是,当试图使用我的表中的细节已登录时,我得到一个'Http 401.0 - 未经授权'页面。
我知道我在电子邮件&密码框中输入的内容与我在数据库中检索到的内容匹配,因为我使用标签进行了测试,并且它们都匹配。如果有帮助,我正在使用ASP.NET 4.5.2。
我的表是简单 -
Email (pk)(varchar) - For logon
Password (varchar) - For logon
First_Name (varchar)
我的代码如下;
UserLogon视图 -
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();
}
LogOn支持视图 -
@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>
你从哪里得到那个错误? –
在浏览器中,那是什么意思? @StephenMuecke – ACostea
什么行代码导致它。 –