Question

I have a null check in code that is checking to see whether a cookie exists in the response object already:

         if (HttpContext.Current.Response.Cookies["CookieName"] != null)
        {
            sessionCookie = HttpContext.Current.Response.Cookies["CookieName"];
            cookieValue = sessionCookie.Value;
        }

When I check through the debugger the key doesn't exist before the check, but it does exists after the check. Thus the return value from the cookie is null. Does checking for a cookies existence automatically create the cookie?

Thanks in advance

Was it helpful?

Solution

This happens because HttpContext.Current is associated with the thread that the request is currently executing on. On a different thread, the framework has no way to know which request you want to use.

There are ways to fix this-- for example .NET's BackgroundWorker can propagate context to another thread. The Asynchronous Pages support in ASP.NET will also propagate context correctly.

So you have two options: either rewrite all your async code to use context-passing async mechanisms like BackgroundWorker or Async Pages, or change your code to check for HttpContext.Current==null before trying to access any properties of HttpContext.Current

OTHER TIPS

That case, when the first answer contains a nonsense not related to the question.

Every time when you do the check:

if (HttpContext.Current.Response.Cookies["CookieName"] != null)

this line of code not only checks, whether a cookie exists, but also creates a new empty cookie. Even Get method creates[1] the new cookie implicitly.

You can use the code like this:

Cookie existing_cookie = null;
foreach (Cookie c in HttpContext.Current.Response.Cookies)
{
    if ("CookieName" == c.Name)
    {
        existing_cookie = c;
        break;
    }
}
if (null != existing_cookie)
{
    // exists
}

Or use LINQ methods to do almost the same.

The answer is yes, calling Response.Cookies["CookieName"] in any manner actually creates the cookie.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top