Skip to main content

A cookie wrapper class. Easily read, create, update and delete cookies in MVC


Create a new class with name CookieHelper.cs In your project and paste the following code.

public class CookieHelper
    {
        #region Constants

        /// <summary>
        /// The cookie name
        /// </summary>
        public const string cookieName = "UserName";

        #endregion

        #region Enums

        public enum EnumCookieInterval
        {
            SECOND = 0,
            MINUTE = 1,
            DAY = 2,
            MONTH = 3,
            YEAR = 4
        };

        #endregion

        #region Utilities

        /// <summary>
        /// Calculates the cookie lifetime.
        /// </summary>
        /// <param name="duration">The duration.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <returns>Expire date for cookie</returns>
        private static DateTime CalculateCookieLifetime(int duration, Enum durationType)
        {
            DateTime cookieExpire = DateTime.Now;

            switch (Convert.ToInt32(durationType))
            {
                case 0:
                    cookieExpire = DateTime.Now.AddSeconds(duration);
                    break;

                case 1:
                    cookieExpire = DateTime.Now.AddMinutes(duration);
                    break;

                case 2:
                    cookieExpire = DateTime.Now.AddDays(duration);
                    break;

                case 3:
                    cookieExpire = DateTime.Now.AddMonths(duration);
                    break;

                case 4:
                    cookieExpire = DateTime.Now.AddYears(duration);
                    break;

                default:
                    cookieExpire = DateTime.Now.AddDays(duration);
                    break;
            }
            return cookieExpire;
        }
        
        #endregion

        #region Methods

        /// <summary>
        /// Creates the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <param name="cookieValue">The cookie value.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        public static string CreateCookie(string cookieName, string cookieValue, Enum durationType, int duration)
        {

            HttpCookie myCookie = new HttpCookie(cookieName);

            // Set the cookie value.
            myCookie.Value = cookieValue;

            // Set the cookie expiration date.
            myCookie.Expires = CalculateCookieLifetime(duration, durationType);

            // Add the cookie.
            //Response.Cookies.Add(myCookie);
            HttpContext.Current.Response.Cookies.Add(myCookie);

            return cookieValue;

        }

        /// <summary>
        /// Reads the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <returns></returns>
        public static string ReadCookie(string cookieName)
        {

            string cookieValue = string.Empty;

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie = HttpContext.Current.Request.Cookies[cookieName];

            // Read the cookie information and display it.
            if (myCookie != null)
                cookieValue = myCookie.Value;


            return cookieValue;
        }

        /// <summary>
        /// Updates the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <param name="cookieValue">The cookie value.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        public static string UpdateCookie(string cookieName, string cookieValue, Enum durationType, int duration)
        {

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie = HttpContext.Current.Request.Cookies[cookieName];

            // Set the cookie value.
            myCookie.Value = cookieValue;

            // Set the cookie expiration date.
            myCookie.Expires = CalculateCookieLifetime(duration, durationType);

            // Add the cookie.
            //Response.Cookies.Add(myCookie);
            HttpContext.Current.Response.Cookies.Add(myCookie);

            return cookieValue;

        }

        /// <summary>
        /// Deletes the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        public static void DeleteCookie(string cookieName)
        {
            HttpCookie myCookie = new HttpCookie(cookieName);

            DateTime cookieExpire = DateTime.Now;

            // Set the cookie expiration date.
            myCookie.Expires = cookieExpire.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(myCookie);

        }

        #endregion
    }



How to use?


1. Create cookie 

string cookie = CookieHelper.CreateCookie(CookieHelper.cookieName, "Here is cookie value", CookieHelper.EnumCookieInterval.DAY, 7);

string cookie = CookieHelper.CreateCookie(CookieHelper.cookieName, "Here is cookie value", CookieHelper.EnumCookieInterval.MONTH, 1);

2. Read Cookie

string cookie = CookieHelper.ReadCookie(CookieHelper.cookieName);

3. Update Cookie

string newCookie = CookieHelper.UpdateCookie(CookieHelper.cookieName, "Updated cookie value", CookieHelper.EnumCookieInterval.DAY, 14);

4. Delete Cookie

CookieHelper.DeleteCookie(CookieHelper.cookieName);

Hope it will helps you. Let me know your thoughts!



Comments

Popular posts from this blog

दान धर्माची बदललेली परिभाषा

नमस्कार! 🙏 मनातले विचार अनेकदा येतात, पण ते शब्दांत मांडण्याचा हा माझा पहिलाच प्रयत्न आहे. त्यामुळे काही चूक-भूल झाली असल्यास समजून घ्यावे. आज WhatsApp आणि Facebookमुळे जग खूप जवळ आले आहे, हे नक्की. पण त्याचबरोबर प्रत्येक गोष्ट share करण्याची जणू सवयच (किंवा छंदच) लागला आहे. मी स्वतःही कधीमधी काही गोष्टी share करतोच, पण मर्यादेत. हल्ली एक गोष्ट प्रकर्षाने जाणवते दानधर्मसुद्धा सोशल मीडियावर मांडला जाऊ लागला आहे. दान करतानाचे फोटो, स्टेटस, पोस्ट्स… जणू त्याचेही मार्केटिंग सुरू झाले आहे. दुर्दैवाने, यामुळे दानाचा मूळ अर्थच विसरला जातो आहे. माझ्या मते, दान हे निस्वार्थ भावनेतून केले गेले पाहिजे ज्यात कोणत्याही परताव्याची अपेक्षा नसते. पण जेव्हा “मी दान करतो” हे दाखवण्यासाठी Facebook पोस्ट, WhatsApp स्टेटस किंवा इतर माध्यमांचा वापर केला जातो, तेव्हा मनात एक प्रश्न उभा राहतो. खरंच हे दान आहे की प्रसिद्धीची इच्छा ठेवून केलेला प्रयत्न? परताव्याची भावना मनात ठेवून केलेले दान मग व्यवहारासारखेच वाटत नाही का? जसा व्यवहारात आपण पैसे देऊन त्याबदल्यात वस्तू किंवा सेवा घेतो, तसंच प्रसिद्धी, क...

How To Create Custom HTML Helper in ASP.NET MVC? Here Is The Way.

In this article, I will explain how to create a custom HTML helper as per your requirement. If you know the MVC and Helpers already, you can skip the next paragraph and if you don't know, here is an explanation about helpers. What are HTML Helpers in MVC? An HTML helper is a method that is used to render the specified html content in View. It can be implemented as an extension method. If you know the ASP.NET webforms, you might know the concept of web controls. e.g. <asp:TextBox /><asp:label /> If you use these controls in web form on browsers, they will converted to their equivalent HTML controls like TextBox will be <input type="text" /> and label will be <span></span> HTML helpers methods are the same as web controls it allows to render appropriate HTML in view. Let's take an example of how HTML helper looks like: @Html.TextBox("Myname","Mayur Lohite") This HTML helper will render the following HTML ...