Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Response inside a static method

Tags:

I have the following static method inside a static class. My question is it safe to use HttpContext.Current.Response inside a static method? I want to be 100% sure that it is thread safe and is only associated with the calling thread.. Does anybody know the answer?

    public static void SetCookie(string cookieName, string cookieVal, System.TimeSpan ts)     {         try         {             HttpCookie cookie =                  new HttpCookie(CookiePrefix + cookieName)                      {Value = cookieVal, Expires = DateTime.Now.Add(ts)};             HttpContext.Current.Response.Cookies.Add(cookie);         }         catch (Exception)         {             return;         }     } 
like image 993
Rippo Avatar asked Nov 13 '09 09:11

Rippo


2 Answers

Yes its quite safe. HttContext.Current will acquire the current HttpContext from the thread that is executing.

Its a common technique and saves you from having to pass the context object around like "Tramp data".

like image 84
AnthonyWJones Avatar answered Sep 22 '22 19:09

AnthonyWJones


HTTPContext.Current is static, so the fact that you're calling it from a static method is irrelevant. What is relevant is that HTTPContext.Current is implemented in such a way that it returns the current thread's HTTP Context, if it exists.

like image 45
Yuliy Avatar answered Sep 19 '22 19:09

Yuliy