开发者

HttpContext Cookie

开发者 https://www.devze.com 2023-02-09 12:52 出处:网络
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(\"myCookie\") && !String.IsNullOrEmpty(HttpContext.Current.Request.Cookies[\"myCookie\"].Value))
if (HttpContext.Current.Request.Cookies.AllKeys.Contains("myCookie") &&
    !String.IsNullOrEmpty(HttpContext.Current.Request.Cookies["myCookie"].Value))
{
    HttpCookie myCookie = HttpContext.Cur开发者_开发百科rent.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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消