HttpContext Cookie

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? From time to time, our website will receive an exception for the link in line 4. I cannot reproduce this in the test.

+3
source share
1 answer

Are you sure you see the exception on line 4, and not on the first line? Your code looks great with one exception: HttpContext.Currentsometimes null, which should result in an exception in your first line of code.

The most common case that you will see is when you use the code inside the background thread, different from the thread that your request is executed on. For example, if you create a thread yourself or execute code in a callback passed to an asynchronous call to the BeginXXX method, you will get zero HttpContext.Current.

- , HttpContext.Current , . , .

: ,.NET BackgroundWorker . ASP.NET .

, : , async , BackgroundWorker Async Pages, , HttpContext.Current==null, HttpContext.Current.

+9

Source: https://habr.com/ru/post/1790752/


All Articles