简体   繁体   English

无法更新asp.net mvc中的cookie

[英]Unable to update cookies in asp.net mvc

I can write and read cookies but I can't change value for existing cookie it always has first set value. 我可以写和读cookie但我不能改变现有cookie的值,它总是有第一个设定值。 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. 根据msdn cookie文件应该是owerwritten。

Each cookie must have a unique name so that it can be identified later when reading it from the browser. 每个cookie必须具有唯一的名称,以便稍后在从浏览器中读取时可以识别它。 Because cookies are stored by name, naming two cookies the same will cause one to be overwritten. 因为cookie是按名称存储的,所以命名两个cookie会导致cookie被覆盖。

Do you have any idea how to fix it? 你知道怎么解决它吗?

I just ran into this exact scenario with a similar block of code: 我刚刚使用类似的代码块遇到了这个确切的场景:

public ActionResult Index(int requestValue)
{
    var name = "testCookie";
    var oldVal = Request.Cookies[name] != null ? Request.Cookies[name].Value : null;
    var val = (!String.IsNullOrWhiteSpace(oldVal) ? oldVal + ";" : null) + requestValue.ToString();

    var cookie = new HttpCookie(name, val)
    {
        HttpOnly = false,
        Secure = false,
        Expires = DateTime.Now.AddHours(1)
    };

    HttpContext.Response.Cookies.Set(cookie);

    return Content("Cookie set.");
}

The first time that code would run, the cookie would be set without incident. 代码第一次运行时,cookie将被设置而不会发生意外。 But any subsequent run would never update it at all (value or expiration). 但任何后续运行都不会更新它(值或到期)。

Turns out, the semi-colon is an illegal character in a cookie value, and trying to delimit your values with it will cause the cookie value to be truncated. 事实证明,分号是cookie值中的非法字符,并且尝试用它来分隔您的值将导致cookie值被截断。 If we change the semi-colon to another character, like a pipe (|), everything works out just fine. 如果我们将分号更改为另一个字符,比如管道(|),那么一切都很好。

Consider the header sent for a cookie value (courtesy of Fiddler): 考虑为cookie值发送的标头(由Fiddler提供):

Response sent 61 bytes of Cookie data: 响应发送了61个字节的Cookie数据:

Set-Cookie: testCookie=2;1; Set-Cookie:testCookie = 2; 1; expires=Tue, 09-Sep-2014 19:23:43 GMT; expires = Tue,09-Sep-2014 19:23:43 GMT; path=/ 路径= /

As we can see, the semi-colon is being used to separate the individual parts of the cookie definition. 我们可以看到,分号用于分隔cookie定义的各个部分。 Thus, if you want to use a semi-colon in cookie value itself, it must be encoded so as not to be misinterpreted. 因此,如果要在cookie值本身中使用分号,则必须对其进行编码,以免误解。 This answer gives a more detailed look into the actual specification: https://stackoverflow.com/a/1969339/143327 . 这个答案给出了更详细的实际规范: https//stackoverflow.com/a/1969339/143327

You can't use a semi-colon, in plain text, as your delimiter. 您不能以明文形式使用分号作为分隔符。

According to the ancient Netscape cookie_spec: 根据古老的Netscape cookie_spec:

This string is a sequence of characters excluding semi-colon, comma and white space. 此字符串是一系列字符,不包括分号,逗号和空格。

You can't directly modify a cookie. 您无法直接修改Cookie。 Instead you are creating a new cookie to overrite the old one. 相反,您正在创建一个新的cookie来覆盖旧的cookie。 http://msdn.microsoft.com/en-us/library/vstudio/ms178194(v=vs.100).aspx http://msdn.microsoft.com/en-us/library/vstudio/ms178194(v=vs.100).aspx

Try 尝试

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

Response.Cookies[Constants.PostsViewing].Value = v;
Response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365);

This should change the client Response instead of the servers Request. 这应该更改客户端响应而不是服务器请求。

In order to use Response.AppendCookie, you first have to get a HttpCookie from your Cookies collection. 要使用Response.AppendCookie,首先必须从Cookies集合中获取HttpCookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM