我正在尝试将会话对象设置为cookie,以便我可能不会重复登录。我的代码是这样的:
[HttpPost]
public ActionResult Login(UserAccount user , [Bind(Include = "ID,NameOfSession")] SessionSave Sessions)
{
using (QuestionsDBContext db = new QuestionsDBContext())
{
var usr = db.userAccount.Single(u => u.UserName == user.UserName && u.Password == user.Password);
Session["UserID"] = usr.UserID.ToString();
Session["Username"] = usr.UserName.ToString();
if (user != null)
{
bool userAutherised = true;
if (userAutherised)
{
//create the authentication ticket
var serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(usr.UserName.ToString());
var authTicket = new FormsAuthenticationTicket(
1,
usr.UserName.ToString(), //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
true, //true to remember
userData, //roles
FormsAuthentication.FormsCookiePath
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
}
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Username or Password is wrong");
}
}
return View();
}
我的索引动作:
[Authorize]
public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page)
{
if (Response.Cookies["Username"] != null)
{
//code here
}
}
不知何故,此代码无效。每次我去索引页面,我都要通过登录。请有人说清楚。