Reputation: 54087
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
?
Upvotes: 6
Views: 6173
Reputation: 887215
Request.Cookies
contains the complete set of cookies, both those that browser send to the server and those that you just created on the server.
Response.Cookies
contains 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:
ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of HttpRequest contains cookies transmitted by the client to the server in the Cookie header. The collection accessed through the Cookies collection of HttpResponse contains new cookies created on the server and transmitted to the client in the Set-Cookie header.
After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.
Your first code sample should work if you make the for
loop run backwards.
The new cookies will be added after the end, so the backwards loop would ignore them.
Upvotes: 12