Sunday, June 1, 2014

Store multiple values in a single cookie using ASP.NET and C#

If you search for storing multiple values in a single cookie using ASP.NET and C#, you may get a wide variety of answers out on the Internet.

However, there is a very easy method to accomplish this provided directly by Microsoft:

The HttpCookie.Values Property is a NameValueCollection that easily allows you to add multiple values to a Cookie simply by indexing into the NameValueCollection to add the appropriate keys and values.

Below is a simple example of how to dynamically create a cookie with a collection of keys and values:
/// <summary>
/// Creates a cookie with the specified NameValueCollection of values
/// </summary>
/// <param name="cookieName"></param>
/// <param name="nvCookie"></param>
public static void CreateCookie(string cookieName, NameValueCollection nvCookie)
    HttpCookie cookie = new HttpCookie(cookieName);
    foreach (string cookieKey in nvCookie)
        cookie.Values[cookieKey] = nvCookie[cookieKey];
}//method: CreateCookie

You can then use this method in the following manner:


NameValueCollection nvCookie = new NameValueCollection();
nvCookie["CustomKey"] = model.CustomValue;
nvCookie["UserName"] = model.UserName;
CookieManager.CreateCookie("MultipleValueCookie", nvCookie);

No comments:

Post a Comment