I am trying to set my session object into cookie, so that I might not have login repeatedly. My code is like this :
[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();
}
And my index action :
[Authorize]
public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page)
{
if (Response.Cookies["Username"] != null)
{
//code here
}
}
Somehow, this code is not working. Every time I go to index page, I have to go through login. Please someone make this clear.