Search code examples
c#asp.nethttpresponsehttpcookie

ASP.NET HttpResponse Cookies null check


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


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