I have been experimenting with code that will clear all of the cookies in an HttpContext.Response.
Initially, I used this:
DateTime cookieExpires = DateTime.Now.AddDays(-1);
for (int i = 0; i < HttpContext.Request.Cookies.Count; i++)
{
HttpContext.Response.Cookies.Add(
new HttpCookie(HttpContext.Request.Cookies[i].Name, null) { Expires = cookieExpires });
}
However, this will error with an OutOfMemoryException because the for loop never exits – each time you add a cookie to the Response, it also gets added to the `Request.
The following approach works:
DateTime cookieExpires = DateTime.Now.AddDays(-1);
List<string> cookieNames = new List<string>();
for (int i = 0; i < HttpContext.Request.Cookies.Count; i++)
{
cookieNames.Add(HttpContext.Request.Cookies[i].Name);
}
foreach (string cookieName in cookieNames)
{
HttpContext.Response.Cookies.Add(
new HttpCookie(cookieName, null) { Expires = cookieExpires });
}
So, what exactly is the relationship between HttpContext.Request.Cookies and HttpContext.Response.Cookies?
Request.Cookiescontains the complete set of cookies, both those that browser send to the server and those that you just created on the server.Response.Cookiescontains the cookies that the server will send back.This collection starts out empty and should be changed to modify the browser’s cookies.
The documentation states:
Your first code sample should work if you make the
forloop run backwards.The new cookies will be added after the end, so the backwards loop would ignore them.