HttpContext.Current.Response inside a static method

Rippo picture Rippo · Nov 13, 2009 · Viewed 16.1k times · Source

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;
        }
    }

Answer

AnthonyWJones picture AnthonyWJones · Nov 13, 2009

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".