Set value to HttpCookie - CSharp System.Web

CSharp examples for System.Web:Cookie

Description

Set value to HttpCookie

Demo Code


using System.Web;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from  w w w .ja  va  2  s.  c o m

public class Main{
        public static void Set(string cookieKey,string itemKey,string cookieValue,DateTime? expires,string cookieDomain = "")
        {
            HttpCookie cookie = HttpContext.Current.Response.Cookies[cookieKey];

            cookie[itemKey] = cookieValue;

            if (!string.IsNullOrEmpty(cookieDomain))
                cookie.Domain = cookieDomain;
            cookie.Path = "/";

            if (expires != null)
                cookie.Expires = expires.Value;

        }
        public static void Set(string cookieKey,string itemKey,string cookieValue)
        {
            Set(cookieKey,itemKey,cookieValue,null);
        }
        public static void Set(string cookieKey,string cookieValue)
        {
            Set(cookieKey,cookieValue,DateTime.MinValue);
        }
        public static void Set(string cookieKey,string cookieValue,DateTime? expires,string cookieDomain = "")
        {
            HttpCookie cookie = new HttpCookie(cookieKey,cookieValue);


            if (!string.IsNullOrEmpty(cookieDomain))
                cookie.Domain = cookieDomain;
            cookie.Path = "/";

            if (expires != null && expires.Value != DateTime.MinValue)
                cookie.Expires = expires.Value;

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
}

Related Tutorials