ASP.NET多线程下使用HttpContext.Current为null解决方案
来源:互联网 发布:windows 10 关闭更新 编辑:程序博客网 时间:2024/05/17 07:07
问题一:多线程下获取文件绝对路径
当我们使用HttpContext.Current.Server.MapPath(strPath)获取绝对路径时HttpContext.Current为null,解决办法如下:
/// /// 获得当前绝对路径 /// /// 指定的路径 /// 绝对路径 public static string GetMapPath(string strPath) { if (strPath.ToLower().StartsWith("http://")) { return strPath; } if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", "\\"); if (strPath.StartsWith("\\") || strPath.StartsWith("~")) { strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } }
问题二:多线程下获取缓存问题
多线程下使用HttpContext.Current.Cache.Get(key)获取缓存时HttpContext.Current为null,解决办法如下:
HttpRuntime.Cache.Get(key);
从MSDN上的解释可以看出,HttpRuntime.Cache是应用程序级别的,而HttpContext.Current.Cache是针对当前WEB上下文定义的。
然而,实际上,这二个都是调用的同一个对象,不同的是:HttpRuntime下的除了WEB中可以使用外,非WEB程序也可以使用。
而HttpContext则只能用在WEB中。因此,在可能的情况下,我们尽可能使用HttpRuntime(然而,在不同应用程序之间如何调用也是一个问题)。
问题三:多线程下使用Html转码问题
多线程下使用HttpContext.Current.Server.HtmlEncode(Htmlstring)转码HttpContext.Current为null,解决办法如下:
HttpUtility.HtmlEncode(Htmlstring)
总之,HttpContext不是万能的,当多线程调用,或是用机器模拟调用时,此时是没有HttpContext上下文的。
详细讲解可以看下这篇文章 http://www.cnblogs.com/fish-li/archive/2011/08/21/2148640.html#_label4
- ASP.NET多线程下使用HttpContext.Current为null解决方案
- ASP.NET多线程下使用HttpContext.Current为null解决方案
- ASP.NET Identity V2在多线程中UserManager获取的httpContext.Current始终为null的解决办法
- .net 多线程下HttpContext.Current 的问题
- ASP.NET 使用HttpContext.Current.Cache
- HttpContext.Current.Session 为null
- HttpContext.Current.Session为null的问题
- ASP.NET HttpContext.Current在新建线程中会返回null
- 多线程下HttpContext.Current 的问题
- 多线程下HttpContext.Current 的问题
- System.Web.HttpContext.Current.Session为NULL值的问题?
- 线程Thread调用时System.Web.HttpContext.Current为NULL
- WCF Service中HttpContext.Current为null的解决办法
- WCF Service中HttpContext.Current为null的解决办法
- 关于System.Web.HttpContext.Current.Session 为 null的问题
- System.Web.HttpContext.Current.Session为NULL值的问题?
- ASP.NET System.Web.HttpContext类Current属性 的运用
- 对于asp.net中的服务器变量HttpContext.Current.Request.ServerVariables
- 手机游戏内存优化
- 常用税收风险管理指标
- 基础搜索算法题解(N-R)
- android 媒体文档
- c++ bug
- ASP.NET多线程下使用HttpContext.Current为null解决方案
- NSValueTransformer
- IplImag to QImage与QImage to IplImage
- 【Android 非常基础】android开发小技巧
- 服务简介
- IOS网络请求时发生“The network connection was lost.”错误
- 关于docker部署的一个简单应用(入门级别)
- sass 入门
- android ProgressBar简单介绍及实例