views:

138

answers:

1

How to delete a specific value in a specific cookie in ASP.NET?

For example: I have a Cookie named 'MyCookie' and it contains the values 'MyCookieValueOne', 'MyCookieValueTwo', 'MyCookieValueThree'.

Now I need to delete the value 'MyCookieValueTwo'.

What should I do?

Can we use any of the following properties to achieve this?

Request.Cookies["MyCookie"].Value
Request.Cookies["MyCookie"].Values

and why?

+1  A: 

Edit: 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);
}

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);
}

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.

Rex M
This will not do the job. I need to delete only one value. But, this will delete the entire Cookie.
Please read the Question again.