Saturday, 1 April 2017

Cookie Helper Class in C#


In this article I will show you Cookie Helper Class in C#.


public static class CookieHelper
    {
        //Set new cookie...
        public static bool Set(string CkName, string CkValue, int CkExpirationMins, 
            string ckDomain, bool ckIsSecure)
        {
            bool flag = false;
            try
            {
                HttpCookie newCookie = new HttpCookie(CkName);
                newCookie.HttpOnly = true;
                newCookie.Value = CkValue;
                newCookie.Expires = DateTime.Now.AddMinutes(CkExpirationMins);
                if (!string.IsNullOrEmpty(ckDomain)) newCookie.Domain = ckDomain;
                if (ckIsSecure) newCookie.Secure = ckIsSecure;
 
                HttpContext.Current.Response.Cookies.Add(newCookie);
                flag = true;
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }
 
        //Read cookie value...
        public static string Get(string CkName)
        {
            string strReturn = "";
            if (!string.IsNullOrEmpty(CkName))
            {
                try
                {
                    HttpCookie currentCookie = (HttpCookie)HttpContext.Current.Request.Cookies[CkName];
                    if (currentCookie != null) strReturn = currentCookie.Value;
                }
                catch (Exception) { }
            }
            return strReturn;
        }
 
    }

No comments:

Post a Comment