HttpContext.Current.Response inside a static method

烂漫一生 提交于 2019-11-29 17:02:39

问题


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

回答1:


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




回答2:


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.




回答3:


It's not clear what do you exactly mean by thread-safety. Yes, HttpContext.Current returns the HttpContext object associated with the current thread. Note that if you call the function on a thread except the one currently processing the request (for example, in an async function call), you wouldn't be able to access the HttpContext object you want.

Another approach is to have the context object passed as an argument to your function.



来源:https://stackoverflow.com/questions/1728175/httpcontext-current-response-inside-a-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!