Skip to content Skip to sidebar Skip to footer

How To Avoid Duplicate Cookie For My Asp.net Application

I am using a client side cookie to carry a data(string), which is helping to use the same data whenever user reopen the browser. My concern there are multiple cookies where create

Solution 1:

Cookie Names are case-sensitive for some browsers such as Chrome and FireFox.

In order to avoid it, you should use a single helper method to create cookie, so that cookie name will be consistent across your site.

For example,

publicclassCookieHelper{
    publicstaticvoid SetCookie(string cookieName, string cookieValue, int days)
    {
        cookieName = cookieName.ToLower();
        var cookie = new HttpCookie(cookieName)
        {
            Value = cookieValue,
            Expires = DateTime.Now.AddDays(days)
        };

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

    publicstaticString GetCookie(string cookieName)
    {
        try
        {
            cookieName = cookieName.ToLower();    
            if (HttpContext.Current.Request.Cookies[cookieName] == null)
                returnstring.Empty;

            return HttpContext.Current.Request.Cookies[cookieName].Value;
        }
        catch
        {
            returnstring.Empty;
        }
    }
}

Post a Comment for "How To Avoid Duplicate Cookie For My Asp.net Application"