您的位置:首页 > 理论基础 > 计算机网络

HttpContext.Current.Server.MapPath("/") 未将对象设置到对象的实例异常。

2017-11-02 09:09 295 查看
多线程中的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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐