管理员登录用户控制器

时间:2011-07-13 22:43:45

标签: linq-to-sql asp.net-mvc-3 hyperlink admin login-control

我正在尝试在MVC3项目中实现管理员的简单登录。我是ASP.NET和MVC3的新手。我用Google搜索并问questions!已经看到很多非常好的方法来实现这个,但它们都处于一个非常抽象的层面,坦率地说,对我来说可能有点高。我在我的数据库中有凭据所以基本上我只想查询那个并重定向用户,如果登录匹配那些,如果不再显示登录表单。所以这就是我得到的。我的模特:

  public class FormModel
{
    public bool isAdmin { get; set; }


 [Required(ErrorMessage = "Please enter your Username")]
 //[Remote("ValidateUserName", "Login", ErrorMessage = "UserName already taken!")]
 [StringLength(6, MinimumLength = 3)]
 [Display(Name = "Username:")]
 [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")] 
 public string UserName { get; set; }

 [Required(ErrorMessage = "Please enter your Password")]
 [DataType(DataType.Password)]
 [Display(Name = "Password:")]
 public string Password { get; set; }

}
 public User IsAdmin(string username, string password) 
   { 
      return (from user in db.Users 
      where user.username == username && user.password == password <--- alternative here is to just match username and pass against the data I have in my db columns(testdata 'admin', 'password')
      && user.IsAdmin == true  
      select user).SingleOrDefault(); 
    }

现在我的控制器基本上就是这样:

   public ActionResult Index()
    {
        //some code here maybe a conditional
        return View();
    }

最后我的观点是:

     @model Web.VoucherCannon.Models.FormModel
     @using (Html.BeginForm("HandleForm", "Login", FormMethod.Post, new {id = "myForm"})) {
@Html.ValidationSummary(true)
        <div class="editor-label">
        @Html.LabelFor(model => model.UserName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.UserName)
        @Html.ValidationMessageFor(model => model.UserName)
    </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>
    <button class="button">Log In</button> 
      }

所以现在。如何在控制器中使用查询的返回结果以便我可以登录?我相信我稍后会重构它并使用dbcontext层等等,但是现在我很乐意让这个工作。感谢帮助!

1 个答案:

答案 0 :(得分:0)

您应该有2个控制器操作:一个用于呈现登录(可在GET上访问)表单,另一个用于处理提交(在POST上可访问)并执行实际身份验证。

// This will render the Login view (the one you have shown)
public ActionResult Login()
{
    var model = new FormModel();
    return View(model);
}

// This one is responsible for handling the submission and credential verification
[HttpPost]
public ActionResult Login(FormModel model)
{
    if (!ModelState.IsValid)
    {
        // The user submit the form but validation 
        // (as defined on the model using DataAnnotation attributes) failed
        // => redisplay the view so that the user can fix his errors
        return View(model);
    }

    // notice that you don't need to pass parameters to the IsAdmin method
    // as it already contains the username and password as properties
    if (!model.IsAdmin()) 
    {
        // The IsAdmin method didn't verify the credentials => add a model error
        // and redisplay the login view
        ModelState.AddModelError("username", "dude you are not an admin");
        return View(model);
    }

    // OK, at this stage everything is fine => we can grant access
    // by issuing an authentication cookie
    FormsAuthentication.SetAuthCookie(model.UserName, false);

    // finally we redirect to some home page for admins
    return RedirectToAction("Index", "Admin");
}