ViewState, Session and the like offer easy ways to insert, and retrieve their values. Cookies are a little tougher. I wanted a one liner utility class to simplify things.
Rick Strahl's Blog to the rescue. I didn't like the one class per cookie and I wanted cookies to automatically persist so I changed things up a bit.
My class is below:
public class Cookie
{
/// <summary>
/// Writes the cookie into the response stream with the value passed. The value
/// is always the UserId.
/// <seealso>Class WebStoreCookie</seealso>
/// </summary>
/// <param name="String Value">
/// Writes a value into the specified cookie.
/// </param>
/// <returns>Void</returns>
public static void WriteCookie(string cookieName, string value, bool persistent, int cookieTimeoutInMonths)
{
HttpCookie cookie = new HttpCookie(cookieName, value);
if (persistent)
cookie.Expires = DateTime.Now.AddMonths(cookieTimeoutInMonths);
HttpContext.Current.Trace.Warn(string.Format("Add {0} value: {1}", cookieName, value));
HttpContext.Current.Response.Cookies.Add(cookie);
}
/// <summary>
/// Writes the cookie into the response stream with the value passed. The value
/// is always the UserId.
/// <seealso>Class WebStoreCookie</seealso>
/// </summary>
/// <param name="String Value">
/// Writes a value into the specified cookie.
/// </param>
/// <returns>Void</returns>
public static void WriteCookie(string cookieName, string value)
{
WriteCookie(cookieName, value, true, 1);
}
/// <summary>
/// Removes the cookie by clearing it out and expiring it immediately.
/// <seealso>Class WebStoreCookie</seealso>
/// </summary>
/// <returns>Void</returns>
public static void Remove(string cookieName)
{
HttpCookie Cookie = HttpContext.Current.Request.Cookies[cookieName];
if (Cookie != null)
{
Cookie.Expires = DateTime.Now.AddHours(-2);
HttpContext.Current.Response.Cookies.Add(Cookie);
}
}
/// <summary>
/// Retrieves the user's Cookie. If the Cookie doesn't exist a new one is generated
/// by hashing a new GUID value and writing the Cookie into the Response.
/// <returns>Customers UserId</returns>
public static string Get(string cookieName)
{
string v;
if (DoesExist(cookieName))
{
HttpCookie Cookie = HttpContext.Current.Request.Cookies[cookieName];
v = (string)Cookie.Value;
}
else
v = string.Empty;
HttpContext.Current.Trace.Warn(string.Format("Get {0} value: {1}", cookieName, v));
return v;
}
/// <summary>
/// Determines whether the cookie exists
/// </summary>
/// <returns></returns>
public static bool DoesExist(string cookieName)
{
HttpCookie Cookie = HttpContext.Current.Request.Cookies[cookieName];
if (Cookie == null)
return false;
return true;
}
}