C# .NET: Get and Set Cookie Values in .NET

11/23/2013 7:51:10 PM

The follow are generic methods used to get and set cookie values in ASP.NET.

using System;
using System.Linq;
using System.Web;

....

public static void Cookies_Set(string key, string value, DateTime expires)
{
	HttpCookie cookie = new HttpCookie(key, value);
	cookie.Expires = expires;
	HttpContext.Current.Response.SetCookie(cookie);
}


public static string Cookies_Get(string key)
{
	string value = "";
	if (HttpContext.Current.Request.Cookies.AllKeys.Contains(key))
	{
		value = HttpContext.Current.Request.Cookies[key].Value;
	}

	return value;
}