zoukankan      html  css  js  c++  java
  • 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);
              }
          }
  • 相关阅读:
    Leetcode Palindrome Linked List
    Leetcode Delete Node in a Linked List
    Leetcode Ugly Number
    Python 列表解析
    Python 生成器以及应用
    Python 迭代器协议以及可迭代对象、迭代器对象
    Python 装饰器
    Python 函数的嵌套
    Python 闭包函数
    Python 名称空间与作用域
  • 原文地址:https://www.cnblogs.com/vaevvaev/p/7770626.html
Copyright © 2011-2022 走看看