Get and Set Multiple values in a single Cookie in ASP.NET

Used Namespaces

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;

Usage of Multiple values Cookie

Dictionary<string, string> keyVal = new Dictionary<string, string>();
keyVal.Add("FirstName", "Lajapathy");
keyVal.Add("LastName", "Arun"); 

StateManagement stateManagement = new StateManagement();
stateManagement.SetMultipleUsingSingleKeyCookies("Data", keyVal);
keyVal = stateManagement.GetMultipleUsingSingleKeyCookies("Data");

Creating Http request
public static HttpRequest GetHttpRequest()
{
   return HttpContext.Current.Request;
}

Creating http response
public static HttpResponse GetHttpResponse()
{
   return HttpContext.Current.Response;
}

Getting single value from the cookie
public string GetIndividualCookies(string cookieKey)
{
   return GetHttpRequest().Cookies[cookieKey].Value;
}

Setting single value to the cookie
public void SetIndividualCookies(string name, string value)
{
   GetHttpResponse().Cookies[name].Value = value;
}

Getting multiple values from single cookie
public Dictionary<string, string> GetMultipleUsingSingleKeyCookies(string cookieName)
{

    //creating dic to return as collection.
    Dictionary<string, string> dicVal = new Dictionary<string, string>(); 

    //Check whether the cookie available or not.
    if (GetHttpRequest().Cookies[cookieName] != null)
    {

        //Creating a cookie.
        HttpCookie cok = GetHttpRequest().Cookies[cookieName];

        if (cok != null)
        {
            //Getting multiple values from single cookie.
            NameValueCollection nameValueCollection = cok.Values; 
   
            //Iterate the unique keys.
            foreach (string key in nameValueCollection.AllKeys)
            {
               dicVal.Add(key, cok[key]);
            }
        }
    } 
    return dicVal
}

Setting multiple values to the single cookie 
public void SetMultipleUsingSingleKeyCookies(string cookieName, Dictionary<string, string> dic)
{
    if (GetHttpRequest().Cookies[cookieName] == null)
    {
        HttpCookie hc = new HttpCookie(cookieName);
 
        //This adds multiple cookie in the same key.
        foreach (KeyValuePair<string, string> val in dic)
        {
            hc[val.Key] = val.Value;
        }
 
        //Setting 2 day expire.
        hc.Expires.Add(new TimeSpan(2, 0, 0, 0));
        GetHttpResponse().Cookies.Add(hc);
    }
}

}
Output

cookies.png

Thanks for reading this blog. Have a nice day.
 

Ebook Download
View all
Learn
View all