1. 程式人生 > >ASP.NET多線程下使用HttpContext.Current為null解決方案

ASP.NET多線程下使用HttpContext.Current為null解決方案

sdn lower null com 獲取文件 .html 模擬 public 一個

問題一:多線程下獲取文件絕對路徑

問題一:多線程下獲取文件絕對路徑

當我們使用HttpContext.Current.Server.MapPath(strPath)獲取絕對路徑時HttpContext.Current為null,解決辦法如下:


      /// 
        /// 獲得當前絕對路徑
        /// 
        /// 指定的路徑
        /// 絕對路徑
        public static string GetMapPath(string strPath)
        {
            if (strPath.ToLower().StartsWith("
http://")) { return strPath; } if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", "\\"
); if (strPath.StartsWith("\\") || strPath.StartsWith("~")) { strPath = strPath.Substring(strPath.IndexOf(\\, 1)).TrimStart(\\); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } }

問題二:多線程下獲取緩存問題

多線程下使用HttpContext.Current.Cache.Get(key)獲取緩存時HttpContext.Current為null,解決辦法如下:

HttpRuntime.Cache.Get(key);

從MSDN上的解釋可以看出,HttpRuntime.Cache是應用程序級別的,而HttpContext.Current.Cache是針對當前WEB上下文定義的。

然而,實際上,這二個都是調用的同一個對象,不同的是:HttpRuntime下的除了WEB中可以使用外,非WEB程序也可以使用。

而HttpContext則只能用在WEB中。因此,在可能的情況下,我們盡可能使用HttpRuntime(然而,在不同應用程序之間如何調用也是一個問題)。

問題三:多線程下使用Html轉碼問題

多線程下使用HttpContext.Current.Server.HtmlEncode(Htmlstring)轉碼HttpContext.Current為null,解決辦法如下:

HttpUtility.HtmlEncode(Htmlstring)

總之,HttpContext不是萬能的,當多線程調用,或是用機器模擬調用時,此時是沒有HttpContext上下文的。

ASP.NET多線程下使用HttpContext.Current為null解決方案