DefconDotNet

CookieStorage

Jun 14th, 2012
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. using System.Web;
  3. using Freelancers.Infrastructure.Helpers;
  4. using Freelancers.Infrastructure.Interfaces;
  5.  
  6. namespace Freelancers.Infrastructure.Implementations
  7. {
  8.     public class CookieStorage : ICookieStorage
  9.     {
  10.         public void Store(string key, string value, DateTime expires)
  11.         {
  12.             Ensure.Argument.NotNullOrEmpty(key, "key");
  13.             Ensure.Argument.NotNullOrEmpty(value, "value");
  14.             Ensure.Argument.InFuture(expires, "expires");
  15.  
  16.             var cookie = HttpContextFactory.Current.Request.Cookies.Get(key);
  17.             if (cookie != null)
  18.             {
  19.                 cookie.Value = value;
  20.                 cookie.Expires = expires;
  21.  
  22.                 HttpContextFactory.Current.Response.SetCookie(cookie);
  23.             }
  24.             else
  25.             {
  26.                 cookie = new HttpCookie(key)
  27.                              {
  28.                                  Value = value,
  29.                                  Expires = expires
  30.                              };
  31.  
  32.                 HttpContextFactory.Current.Response.Cookies.Add(cookie);
  33.             }
  34.         }
  35.  
  36.         public string Retrieve(string key)
  37.         {
  38.             Ensure.Argument.NotNullOrEmpty(key, "key");
  39.  
  40.             var cookie = HttpContextFactory.Current.Request.Cookies[key];
  41.  
  42.             return cookie == null ? null : cookie.Value;
  43.         }
  44.  
  45.         public void Remove(string key)
  46.         {
  47.             Ensure.Argument.NotNullOrEmpty(key, "key");
  48.  
  49.             var cookie = HttpContextFactory.Current.Response.Cookies[key];
  50.  
  51.             if (cookie != null)
  52.                 cookie.Expires = DateTime.Now.AddDays(-1);
  53.  
  54.             HttpContextFactory.Current.Request.Cookies.Remove(key);
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment