HttpContext.Current.Server.MapPath("/") 未將對象設置到對象的實例異常。


多線程中的System.Web.HttpContext.Current.Server.MapPath("/")

多線程中Server.MapPath會失效。。。 

 網上找到幾種解決方法,現在整理如下:

第一種: 

System.Web.HttpContext.Current.Server.MapPath("/")  這個常用來表示網站的根目錄,但是在多線程中,會發生未將對象引用設置到對象的實例。 所以不要分布在不同的類中,盡量在一個全局位置,然后其它類共用這個,畢竟網站的目錄是不會改變的,可以用一個靜態變量表示。

該方法:不太好; 

第二種:

如果需要是WEB應用的目錄下就很好辦啊。假設web根目錄為:c:\www,而DB放在www目錄下的話則可以這樣。  System.AppDomain.CurrentDomain.BaseDirectory.ToString() + ConfigurationManager.AppSettings["dbPath"]就可以了
我找到辦法了,就是上面的

這個是一種方法,就是將路徑下載配置文件中從配置文件讀取,感覺還行。 

第三種:

在多線程里面使用HttpContext.Current,HttpContext.Current是得到null的.    20150703 解釋下為什么當前請求上下文會為null,因為多線程情況下,當前線程可能並非http請求處理線程,根本沒發生請求,所以無法獲取到HttpContext就是null.

這么用:       

public static string MapPath(string strPath)
      {
          if (HttpContext.Current != null)
          {
              return HttpContext.Current.Server.MapPath(strPath);//有http請求
          }
          else //非web程序引用         
          {
              strPath = strPath.Replace("/", "\\");
              if (strPath.StartsWith("\\"))
              {
                  //strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');                            strPath = strPath.TrimStart('\\');               
              }
              return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
          }
      }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM