Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext Cookie

Tags:

c#

asp.net

if (HttpContext.Current.Request.Cookies.AllKeys.Contains("myCookie") &&
    !String.IsNullOrEmpty(HttpContext.Current.Request.Cookies["myCookie"].Value))
{
    HttpCookie myCookie = HttpContext.Current.Request.Cookies["myCookie"];
}

Is there something wrong with this code? Every once in a while, our production website will get a null reference exception on line 4. I can't reproduce this in test.

like image 415
harmony Avatar asked Feb 08 '11 15:02

harmony


1 Answers

Are you sure you're seeing the exception on Line 4 and not the first line? Your code looks fine with one exception: HttpContext.Current is sometimes null, which should cause an exception on your first line of code.

The most common case you'll see this is when you're running code inside a background thread different from the thread that your request is executing on. For example, if you create a thread yourself, or if you execute code in a callback passed into a BeginXXX asynchronous method call, you'll get a null HttpContext.Current.

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.

like image 189
Justin Grant Avatar answered Oct 29 '22 09:10

Justin Grant