zoukankan      html  css  js  c++  java
  • ASP.NET多线程下使用HttpContext.Current为null解决方案

    ASP.NET多线程下使用HttpContext.Current为null解决方案

    前言

             最近将动力起航的站内搜索功能进行了改造,使用了Lucene.Net+盘古分词实现了完整的站内搜索功能(此功能改造将另开章节跟大家讲讲,需要源码的可以留下邮箱,下一章节也会贴出来),本章主要讲讲在改造过程中使用多线程使用HttpContext.Current为null的问题而总结的几个方法,希望大家多多提意见和建议,这样我才能提高,深感闭门造车的苦恼,希望向园子里的大牛们学习!

     问题一:多线程下获取文件绝对路径

         当我们使用HttpContext.Current.Server.MapPath(strPath)获取绝对路径时HttpContext.Current为null,解决办法如下:

    复制代码
            #region 获得当前绝对路径
            /// <summary>
            /// 获得当前绝对路径
            /// </summary>
            /// <param name="strPath">指定的路径</param>
            /// <returns>绝对路径</returns>
            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);
                }
            }
            #endregion
    复制代码

    问题二:多线程下获取缓存问题

             多线程下使用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(然而,在不同应用程序之间如何调用也是一个问题)。

    具体的大家可以参考此博文:http://www.cnblogs.com/McJeremy/archive/2008/12/01/1344660.html

    问题三:多线程下使用Html转码问题

              多线程下使用HttpContext.Current.Server.HtmlEncode(Htmlstring)转码HttpContext.Current为null,解决办法如下:

         HttpUtility.HtmlEncode(Htmlstring)

     结束语

             从以上可以看出,在可能的情况下,我们应该尽可能的使用应用程序级别的方法,这样避免不必要的错误!

  • 相关阅读:
    Coroutine 协程
    jQuery Ajax calls and the Html.AntiForgeryToken()
    CSRF in asp.net mvc and ap.net core
    What is the difference between XSS and CSRF from their execution perspective?
    cocos2d制作动态光晕效果基础——blendFunc
    很有设计感的世界杯
    cocos2d-x (Android)之-那些常见的error记
    cocos2dx libcurl
    如何在遍历中使用 iterator/reverse_iterator 删除元素
    Android ndk下用AssetManager读取assets的资源
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3249100.html
Copyright © 2011-2022 走看看