ASP.NET Generic Cookie Utility Class

Sometimes the simplest things can be the most useful. Using cookies to persist form field values can often be preferable to using Session, Cache or other ASP.NET features. But cookie code can get ugly fast - littering each page with repetitive lines of code that can become difficult to maintain. Why not abstract the function away into a generic "cookie utility" class that can be accessed from anywhere in the application, with an absolute minimum of code?

Stick this CookieUtil class into your ASP.NET application, and the problem is solved.

Here is the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PAB.Web
{
        public static class CookieUtil
        {

        public static string GetCookieValue (string cookieName)
        {
          string cookieVal = String.Empty;
            cookieVal = HttpContext.Current.Request.Cookies[cookieName].Value;
           return cookieVal;
        }

        public static void CreateCookie (string cookieName, string value, int? expirationDays)
        {
            HttpCookie Cookie = new HttpCookie(cookieName, value);
             if ( expirationDays.HasValue )
                Cookie.Expires = DateTime.Now.AddDays(expirationDays.Value );
             HttpContext.Current.Response.Cookies.Add(Cookie);
        }

         public static void DeleteCookie (string cookieName)
        {
            HttpCookie Cookie = HttpContext.Current.Request.Cookies[cookieName];
             if (Cookie != null)
            {
                Cookie.Expires = DateTime.Now.AddDays(-2);
                 HttpContext.Current.Response.Cookies.Add(Cookie);
             }
        }

        public static bool CookieExists(string cookieName)
        {
            bool exists = false;
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
             if (cookie != null)
                exists = true;
            return exists;
        }

         public static Dictionary<string, string> GetAllCookies()
        {
            Dictionary<string, string> cookies = new Dictionary<string, string>();
            foreach (string key in HttpContext.Current.Request.Cookies.AllKeys)
             {
                 cookies.Add(key, HttpContext.Current.Request.Cookies[key].Value);
             }
             return cookies;
        }

         public static void DeleteAllCookies ()
        {
            var x = HttpContext.Current.Request.Cookies;
            foreach (HttpCookie cook in x)
            {
                DeleteCookie(cook.Name);
            }
        }
    }
}

The above code should be pretty much self explanatory. The only item of note that I would point out is that I've made the expirationDays parameter of the CreateCookie method a nullable type so that if the value passed is null, you get a non-persistent cookie (one with no expiration date).

The sample Visual Studio 2010 ASP.NET demo app has two pages - default allows you to enter a first and last name, email, and address. When you click the Save button, it persists these values in the cookie collection:

protected void Submit_Click(object sender, EventArgs e)
         {
             CookieUtil.CreateCookie("firstName",firstname.Text,10);
             CookieUtil.CreateCookie("lastName", lastname.Text, 10);
             CookieUtil.CreateCookie("email", email.Text, 10);
             CookieUtil.CreateCookie("address", addr.Text, 10);
             Response.Redirect("NextPage.aspx");
        }

The Page_Load handler of the Default page looks for all the cookies and restores the values of the form controls if the page is returned to from somewhere else:

protected void Page_Load(object sender, EventArgs e)
         {
             if (CookieUtil.CookieExists("firstName"))
                firstname.Text = CookieUtil.GetCookieValue("firstName");
            if (CookieUtil.CookieExists("lastName"))
                lastname.Text += " " + CookieUtil.GetCookieValue("lastName");
            if (CookieUtil.CookieExists("email"))
               email.Text += " " + CookieUtil.GetCookieValue("email");
            if (CookieUtil.CookieExists("address"))
                addr.Text += " " + HttpUtility.UrlDecode(CookieUtil.GetCookieValue("address"));
        }

Finally, the Delete All button deletes all the cookies:

protected void bntDelete_Click(object sender, EventArgs e)
         {
             CookieUtil.DeleteCookie("firstName");
            CookieUtil.DeleteCookie("lastName");
            CookieUtil.DeleteCookie("email");
            CookieUtil.DeleteCookie("address");
            Response.Redirect("NextPage.aspx");
        }

When you "Save" you are redirected to "NextPage.aspx" which simply retrieves the cookies and populates a label with the values as a proof of concept.  There are also GetAllCookies and DeleteAllCookies methods.

You can download the Visual Studio 2010 ASP.NET solution here.

By Peter Bromberg   Popularity  (5522 Views)