线程编程中用到HttpContext.Current的方法封装

在线程编程时能够为我们的性能提高不少,但是线程不是请求所以请求上下文我们就不能够用到!我在编程时遇到的几个地方留下个映像,同时也希望给不知道的同志们留个纪念!!!

    1.缓存(Cache):我们通常会从System.Web.HttpContext.Current.Cache获取,但是在线程中我们所得到的 HttpContext.Current为null,所以我们得通过System.Web.HttpRuntime.Cache获得缓存实例,我们可以封 装一个方法,这样我们就可以不用管他是在哪里都可以调用当前缓存了。代码如下:
 1  public   class  Cacher
 2 {
 3      private  Cacher() { }
 4 
 5      private   static   readonly  Cache cache;
 6 
 7      static  Cacher() {
 8          HttpContext context  =  HttpContext.Current;
 9          if  (context  ==   null )
10              cache  =  context.Cache;
11          else
12              cache  =  HttpRuntime.Cache;
13      }
14  }

    2.获取文件的物理路径:通常我们会用System.Web.HttpContext.Current.Request来获取当前的物理等有关路径或 URL,通过System.Web.HttpContext.Current.Server.MapPath方法来获取当前文件或目录的物理路径。和上面 一样在线程中这是解决不了问题的,我们可以通过应用程序域 (System.AppDomain.CurrentDomain.BaseDirectory)来获得根目录。
 1           public   static   string  RootPath() {
 2               return  RootPath( " / " );
 3          }
 4 
 5           public   static   string  RootPath( string  filePath)
 6          {
 7               string  rootPath  =  AppDomain.CurrentDomain.BaseDirectory;
 8               string  separator  =  Path.DirectorySeparatorChar.ToString();
 9              rootPath  =  rootPath.Replace( " / " , separator);
10               if  (filePath  !=   null )
11              {
12                  filePath  =  filePath.Replace( " / " , separator);
13                   if  (((filePath.Length  >   0 &&  filePath.StartsWith(separator))  &&  rootPath.EndsWith(separator))
14                  {
15                      rootPath  =  rootPath  +  filePath.Substring( 1 );
16                  }
17                   else
18                  {
19                      rootPath  =  rootPath  +  filePath;
20                  }
21              }
22               return  rootPath;
23          }
24 
25           public   string  PhysicalPath( string  path)
26          {
27               return  (RootPath().TrimEnd( new   char [] { Path.DirectorySeparatorChar })
                +  Path.DirectorySeparatorChar.ToString()  +  path.TrimStart( new   char [] { Path.DirectorySeparatorChar }));
28          }
29 
30           public   string  MapPath( string  path)
31          {
32              HttpContext context  =  HttpContext.Current;
33               if  (context  !=   null )
34              {
35                   return  context.Server.MapPath(path);
36              }
37               return  PhysicalPath(path.Replace( " / " , Path.DirectorySeparatorChar.ToString()).Replace( " ~ " "" ));
38          }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值