標籤:color serve trim 對象 ati 上下 路徑 解決辦法如下 msdn
問題一:多線程下擷取檔案絕對路徑
問題一:多線程下擷取檔案絕對路徑
當我們使用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解決方案