HttpContext.Current.Server.MapPath("/") 未將對象設置到對象的實例異常。
阿新 • • 發佈:2017-11-02
manage bstr director pub tpc 引用 對象引用 失效 settings
多線程中的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); } }
HttpContext.Current.Server.MapPath("/") 未將對象設置到對象的實例異常。