Beware accessing Response.Cookies
I learned something new about ASP.NET today that I had never come across before. I was writing code that looked something like this:
private void CheckForFormsLogout(HttpContext ctx)
{
if (ctx.User.Identity.IsAuthenticated)
{
var logoutCookie = ctx.Response.Cookies[FormsAuthentication.FormsCookieName];
if (logoutCookie != null)
{
var now = DateTime.UtcNow;
if (DateTime.MinValue < logoutCookie.Expires && logoutCookie.Expires < now)
{
// yes, user is logging out
}
}
}
}
Turns out this code has a serious flaw that is actually triggering the logout. The issue is how I was checking for the cookie on the Response.Cookies collection. Turns out that the CookieCollection class creates a cookie if the one you’re asking for doesn’t exist. So in my attempt to see if the cookie was present, I was creating it. The newly created cookie was empty and thus had the side effect of replacing the valid forms authentication cookie with an empty value.
Here’s the change I made to correct the problem:
private void CheckForFormsLogout(HttpContext ctx)
{
if (ctx.User.Identity.IsAuthenticated)
{
if (ctx.Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
{
var logoutCookie = ctx.Response.Cookies.Get(FormsAuthentication.FormsCookieName);
if (logoutCookie != null)
{
var now = DateTime.UtcNow;
if (DateTime.MinValue < logoutCookie.Expires && logoutCookie.Expires < now)
{
// yes the user is logging out
}
}
}
}
}
The same issue applies to Request.Cookies.
You learn something new every day :)

Huh. That’s pretty odd. But wouldn’t you say that reading from Response.Cookies (as opposed to Request.Cookies) represents a practice that should be avoided?