MVC登录存储库?

时间:2015-08-18 07:41:39

标签: asp.net-mvc

我正在尝试使用登录视图,控制器和存储库验证用户

动作导致控制器

[HttpPost]
public ActionResult Login(Models.UserModel user)
{
    CartLibrary.Repository.UserRepository objuserrepository = new CartLibrary.Repository.UserRepository();
     objuserrepository.Login(user.Username, user.Password);
    return RedirectToAction("Index", "Orders"); 
}
public ActionResult Logout()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
}

存储库中的方法

public string Login(string Username, string Password )
{
    if (!DB.Users.Any(x => x.Username == Username && x.Password == Password))
    {
        return Username;
    }
    throw new UnauthorizedAccessException();
    return Username;
}

1 个答案:

答案 0 :(得分:1)

在你的登录方法中,你只需返回字符串(用户名).....但你不要设置任何cookie ...... ????

所以你可以在登录方法后写代码:

    if(String.IsNullOrEmpty(objuserrepository.Login(user.Username,user.Password))
{
  FormsAuthentication.SetAuthCookie(
                 this.TextBox_username.Text.Trim(), flase);

         FormsAuthenticationTicket ticket1 = 
            new FormsAuthenticationTicket(
                 1,                                   // version
                 this.TextBox_username.Text.Trim(),   // get username  from the form
                 DateTime.Now,                        // issue time is now
                 DateTime.Now.AddMinutes(10),         // expires in 10 minutes
                 false,      // cookie is not persistent
                 "HR"                              // role assignment is stored
                 // in userData
                 );
          HttpCookie cookie1 = new HttpCookie(
            FormsAuthentication.FormsCookieName, 
            FormsAuthentication.Encrypt(ticket1) );
          Response.Cookies.Add(cookie1);
}