我正在尝试使用登录视图,控制器和存储库验证用户
[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;
}
答案 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);
}