ASP.NET Cookie子值删除 [英] ASP.NET Cookie Sub-Value Deletion

查看:60
本文介绍了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子值删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆