asp.net-mvcasp.net-mvc-4cookieskey-value

How to save and read Cookie in Asp.net Mvc


I save my cookie as the following code:

public static void SetCookie(string key, string value, int expireDay = 1)
{
        var cookie = new HttpCookie(key , value);
        cookie.Expires = DateTime.Now.AddDays(expireDay);
        HttpContext.Current.Response.Cookies.Add(cookie);
}

The cookie values when stored are as follows: enter image description here

Read Cookie:

public static string GetCookie(string key)
{
        string value = string.Empty;

        var cookie = HttpContext.Current.Request.Cookies[key];

        if (cookie != null)
        {
            if (string.IsNullOrWhiteSpace(cookie.Value))
            {
                return value;
            }
            value = cookie.Value;
        }

        return value;
}

The problem is that when reading the cookie, all the values are empty according to the image below:

enter image description here


Solution

  • The maximum size of a cookie is 4kb.

    Reference: https://docs.devexpress.com/AspNet/11912/common-concepts/cookies-support/cookie-limitations?v=20.1