ASP.NET Cookie子值删除

编程入门 行业动态 更新时间:2024-10-28 15:34:26
本文介绍了ASP.NET Cookie子值删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何删除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子值删除

本文发布于:2023-11-09 22:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ASP   NET   Cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!