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

來源:互聯網
上載者:User

標籤: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解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.