如何删除ASP.NET中特定Cookie中的特定值?
How to delete a specific value in a specific cookie in ASP.NET?
例如:我有一个名为'MyCookie'的Cookie。 ,它包含值'MyCookieValueOne','MyCookieValueTwo','MyCookieValueThree'。
For example: I have a Cookie named 'MyCookie' and it contains the values 'MyCookieValueOne', 'MyCookieValueTwo', 'MyCookieValueThree'.
现在我需要删除值'MyCookieValueTwo'。
我该怎么办?
我们可以使用以下任何属性来实现这一目标吗?
Can we use any of the following properties to achieve this?
Request.Cookies["MyCookie"].Value Request.Cookies["MyCookie"].Values以及为什么?
推荐答案编辑:好的,误解了问题。 HttpCookie.Values是一个NameValueCollection,因此您可以修改该集合-但您需要重新发送cookie作为新的cookie,以覆盖旧的cookie:
OK, misread the question. HttpCookie.Values is a NameValueCollection, so you can modify that collection - but you will need to re-send the cookie as a new one to overwrite the old one:
HttpCookie cookie = Request.Cookies["MyCookie"]; if(cookie != null) { cookie.Values.Remove("KeyNameToRemove"); Response.AppendCookie(cookie); }要删除整个cookie,您必须使其过期-更改它的到期日期,然后重新发送给客户端:
To "delete" an entire cookie you have to "expire" it - change its expiration date and re-send it to the client:
HttpCookie cookie = Request.Cookies["MyCookie"]; if(cookie != null) { cookie.Expires = DateTime.Today.AddMonths(-1); Response.AppendCookie(cookie); }不幸的是,在.NET中使用cookie不仅仅是一点直觉。 AddMonths()有点随意。我用了一个月,您可以使用任何东西-只需确保将过期日期设置为相对于接收计算机时钟的过去日期即可。
Working with cookies in .NET is more than a little unintuitive, unfortunately. The AddMonths() is kinda arbitrary. I use one month, you could use anything - just need to make sure the Expires date is set in the past relative to the receiving computer's clock.
更多推荐
ASP.NET Cookie子值删除
发布评论