Quantcast
Channel: User mykhailovskyi - Stack Overflow
Viewing all articles
Browse latest Browse all 29

Unable to update cookies in asp.net mvc

$
0
0

I can write and read cookies but I can't change value for existing cookie it always has first set value. I found few ways how it can be implemented but no one works. Here is my code:

private void AddPost(string key)
    {
        var context = System.Web.HttpContext.Current;
        var request = context.Request;
        var response = context.Response;

        var cookie = request.Cookies[Constants.PostsViewing];

        if (cookie == null || string.IsNullOrEmpty(cookie.Value))
        {
            response.Cookies.Add(new HttpCookie(Constants.PostsViewing, key)
            {
                Expires = DateTime.Now.AddDays(365)
            });
        }
        else
        {
            if (cookie.Value.Split(';').Contains(key))
            {
                return;
            }

            var v = cookie.Value + ";" + key;

            cookie.Value = v;
            cookie.Expires = DateTime.Now.AddDays(365);
            response.Cookies.Add(cookie);

            // this way also doesn't work
            //cookie.Value = v;
            //response.AppendCookie(cookie);

            // and this
            //response.Cookies[Constants.PostsViewing].Value = v;
            //response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365);
        }

    }

According to msdn cookie file should be owerwritten.

Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.

Do you have any idea how to fix it?


Viewing all articles
Browse latest Browse all 29

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>