Monday, February 17, 2014

cookies and session variables in modern ASP.NET MVC

Here is how to set cookies and session variables in modern ASP.NET MVC. This is a method from a controller:

private void SetIdentity(string id)
{
   IClock clock = ObjectFactory.GetInstance<IClock>();
   string carat = "^";
   if (id != null && id.Contains(carat))
   {
      string[] instructionAndIdentity = id.Replace("^^", ".").Replace("||",
            "+").Split(carat.ToCharArray());
      string pipeSymbol = "|";
      if (instructionAndIdentity[1].Contains(pipeSymbol))
      {
         if (instructionAndIdentity[0] == MagicStrings.MakeCookieOnMatch)
         {
            HttpCookie cookie = new HttpCookie(MagicStrings.IdentityName,
                  instructionAndIdentity[1]);
            cookie.Expires = clock.GiveTime().AddDays(30);
            Response.Cookies.Add(cookie);
         } else {
            HttpCookie cookie = new HttpCookie(MagicStrings.IdentityName, "");
            cookie.Expires = clock.GiveTime();
            Response.Cookies.Add(cookie);
         }
         HttpContext.Session[MagicStrings.IdentityName] = instructionAndIdentity[1];
      }
   }
}

 
 

There is plenty of noise here, but I think you can see what you need beyond what I wrote for myself for a project I am tinkering with. Note how a cookie is destroyed by being set to nothing. You may comparably kill a session variable by setting it to null or an empty string. Here is how to fish for the settings once they are set. Again, forgive the noise. Again, this is a method in a controller.

protected Person GetIdentity()
{
   IPersonRepository personRepository =
         ObjectFactory.GetInstance<IPersonRepository>();
   HttpCookie cookie = Request.Cookies[MagicStrings.IdentityName];
   if (cookie != null)
   {
      string emailAndPassword = cookie.Value;
      if (emailAndPassword.Contains("|"))
      {
         return PersonFinder.FindPersonByEncryptedPassword(emailAndPassword,
               personRepository);
      }
   }
   if (HttpContext.Session[MagicStrings.IdentityName] != null)
   {
      string emailAndPassword = HttpContext.Session[MagicStrings.IdentityName] as
            string;
      if (emailAndPassword != null && emailAndPassword.Contains("|"))
      {
         return PersonFinder.FindPersonByEncryptedPassword(emailAndPassword,
               personRepository);
      }
   }
   return null;
}

 
 

Addendum 2/18/2014: The way I am destroying cookies above is bad as it turns out. Please see this instead.

No comments:

Post a Comment