1、场景

在导入通讯录过程中,把导入的失败、成功的号码数进行统计,然后保存到session中,客户端通过轮询显示状态。

在实现过程中,使用的async调用方法,出现HttpContext.Current为null的情况,如下:

2、网络解答

从百度与谷歌查询,分以下两种情况进行解答:

1、更改web.config配置文件

Stackoverflow给出如下解决方案:http://stackoverflow.com/questions/18383923/why-is-httpcontext-current-null-after-await

2、缓存HttpContext

博客地址:http://www.cnblogs.com/pokemon/p/5116446.html

本博客,给出了异步下HttpContext.Current为空的原因分析。本文中的最后提取出如下方法:

using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Web; namespace TxSms
{
/// <summary>
/// 解决Asp.net Mvc中使用异步的时候HttpContext.Current为null的方法
/// <remarks>
/// http://www.cnblogs.com/pokemon/p/5116446.html
/// </remarks>
/// </summary>
public static class HttpContextHelper
{
/// <summary>
/// 在同步上下文中查找当前会话<see cref="System.Web.HttpContext" />对象
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static HttpContext FindHttpContext(this SynchronizationContext context)
{
if (context == null)
{
return null;
}
var factory = GetFindApplicationDelegate(context);
return factory?.Invoke(context).Context;
} private static Func<SynchronizationContext, HttpApplication> GetFindApplicationDelegate(SynchronizationContext context)
{
Delegate factory = null;
Type type = context.GetType();
if (!type.FullName.Equals("System.Web.LegacyAspNetSynchronizationContext"))
{
return null;
}
//找到字段
ParameterExpression sourceExpression = Expression.Parameter(typeof(SynchronizationContext), "context");
//目前支持 System.Web.LegacyAspNetSynchronizationContext 内部类
//查找 private HttpApplication _application 字段
Expression sourceInstance = Expression.Convert(sourceExpression, type);
FieldInfo applicationFieldInfo = type.GetField("_application", BindingFlags.NonPublic | BindingFlags.Instance);
Expression fieldExpression = Expression.Field(sourceInstance, applicationFieldInfo);
factory = Expression.Lambda<Func<SynchronizationContext, HttpApplication>>(fieldExpression, sourceExpression).Compile(); //返回委托
return ((Func<SynchronizationContext, HttpApplication>)factory);
} /// <summary>
/// 确定异步状态的上下文可用
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static HttpContext Check(this HttpContext context)
{
return context ?? (context = SynchronizationContext.Current.FindHttpContext());
}
}
}

3、实现

通过2对两种方法都进行尝试,发现还是不可用的。使用session共享数据行不通,换另外一种思路,使用cache,封装类库如下:

using System;
using System.Collections;
using System.Web;
using System.Web.Caching; namespace TxSms
{
/// <summary>
/// HttpRuntime Cache读取设置缓存信息封装
/// <auther>
/// <name>Kencery</name>
/// <date>2015-8-11</date>
/// </auther>
/// 使用描述:给缓存赋值使用HttpRuntimeCache.Set(key,value....)等参数(第三个参数可以传递文件的路径(HttpContext.Current.Server.MapPath()))
/// 读取缓存中的值使用JObject jObject=HttpRuntimeCache.Get(key) as JObject,读取到值之后就可以进行一系列判断
/// </summary>
public static class HttpRuntimeCache
{
/// <summary>
/// 设置缓存时间,配置(从配置文件中读取)
/// </summary>
private const double Seconds = 30 * 24 * 60 * 60; /// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value)
{
return Set(key, value, null, DateTime.Now.AddSeconds(Seconds), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
} /// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, string path)
{
try
{
var cacheDependency = new CacheDependency(path);
return Set(key, value, cacheDependency);
}
catch
{
return false;
}
} /// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, CacheDependency cacheDependency)
{
return Set(key, value, cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
} /// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, double seconds, bool isAbsulute)
{
return Set(key, value, null, (isAbsulute ? DateTime.Now.AddSeconds(seconds) : Cache.NoAbsoluteExpiration),
(isAbsulute ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(seconds)), CacheItemPriority.Default, null);
} /// <summary>
/// 获取缓存对象
/// </summary>
public static object Get(string key)
{
return GetPrivate(key);
} /// <summary>
/// 判断缓存中是否含有缓存该键
/// </summary>
public static bool Exists(string key)
{
return (GetPrivate(key) != null);
} /// <summary>
/// 移除缓存对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
HttpRuntime.Cache.Remove(key);
return true;
} /// <summary>
/// 移除所有缓存
/// </summary>
/// <returns></returns>
public static bool RemoveAll()
{
IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator();
while (iDictionaryEnumerator.MoveNext())
{
HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key));
}
return true;
} /// <summary>
/// 设置缓存
/// </summary>
public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime,
TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
{
if (string.IsNullOrEmpty(key) || value == null)
{
return false;
}
HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority, cacheItemRemovedCallback);
return true;
} /// <summary>
/// 获取缓存
/// </summary>
private static object GetPrivate(string key)
{
return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
}
}
}

在此调试,完全可以找到((ImportContactStateModel)model).SuccessNum,如下图:

异步 HttpContext.Current 为空null 另一种解决方法的更多相关文章

  1. WORD 的 Open 和Workbook 的 LoadFromFile 函数返回null的一种解决方法

    WORD Application.Documents.Open 和 Workbook workbookExcel.LoadFromFile 函数返回null的一种解决方法 DCOM Config Se ...

  2. WORD Application.Documents.Open函数返回null的一种解决方法

    DCOM Config Setting for "Microsoft Office Word 97 - 2003 Document" 内部配置一切正常,但调用Application ...

  3. System.Web.HttpContext.Current.Session为NULL解决方法

    http://www.cnblogs.com/tianguook/archive/2010/09/27/1836988.html 自定义 HTTP 处理程序,从IHttpHandler继承,在写Sys ...

  4. 为什么获取的System.Web.HttpContext.Current值为null,HttpContext对象为null时如何获取程序(站点)的根目录

    ASP.NET提供了静态属性System.Web.HttpContext.Current,因此获取HttpContext对象就非常方便了.也正是因为这个原因,所以我们经常能见到直接访问System.W ...

  5. System.Web.HttpContext.Current.Session为NULL值的问题?

    自定义 HTTP 处理程序,从IHttpHandler继承,在写System.Web.HttpContext.Current.Session["Value"]的时 候,没有问题,但 ...

  6. c# 异步方法中HttpContext.Current为空

    调用异步方法前 HttpContext context = System.Web.HttpContext.Current; HttpRuntime.Cache.Insert("context ...

  7. 百度编辑器ueditor 异步加载时,初始化没办法赋值bug解决方法

    百度编辑器ueditor 异步加载时,初始化没办法赋值bug解决方法 金刚 前端 ueditor 初始化 因项目中使用了百度编辑器——ueditor.整体来说性能还不错. 发现问题 我在做一个编辑页面 ...

  8. 异步 HttpContext.Current实现取值的方法(解决异步Application,Session,Cache...等失效的问题)

    在一个项目中,为了系统执行效率更快,把一个经常用到的数据库表通过dataset放到Application中,发现在异步实现中每一次都会出现HttpContext.Current为null的异常,后来在 ...

  9. HttpContext.Current.User is null after installing .NET Framework 4.5

    故障原因:从framework4.0到framework4.5的升级过程中,原有的form认证方式发生了变化,所以不再支持User.Identity.Name原有存储模式(基于cookie),要恢复这 ...

随机推荐

  1. nodejs进阶(4)—读取图片到页面

    我们先实现从指定路径读取图片然后输出到页面的功能. 先准备一张图片imgs/dog.jpg. file.js里面继续添加readImg方法,在这里注意读写的时候都需要声明'binary'.(file. ...

  2. excel 日期/数字格式不生效需要但双击才会生效的解决办法

    原因: Excel2007设置过单元格格式后,并不能立即生效必须挨个双击单元格,才能生效.数据行很多.效率太低. 原因:主要是一些从网上拷贝过来的日期或数字excel默认为文本格式或特殊-中文数字格式 ...

  3. 红黑树——算法导论(15)

    1. 什么是红黑树 (1) 简介     上一篇我们介绍了基本动态集合操作时间复杂度均为O(h)的二叉搜索树.但遗憾的是,只有当二叉搜索树高度较低时,这些集合操作才会较快:即当树的高度较高(甚至一种极 ...

  4. 使用技术手段限制DBA的危险操作—Oracle Database Vault

    概述 众所周知,在业务高峰期,某些针对Oracle数据库的操作具有很高的风险,比如修改表结构.修改实例参数等等,如果没有充分评估和了解这些操作所带来的影响,这些操作很可能会导致故障,轻则导致应用错误, ...

  5. 【Web动画】SVG 线条动画入门

    通常我们说的 Web 动画,包含了三大类. CSS3 动画 javascript 动画(canvas) html 动画(SVG) 个人认为 3 种动画各有优劣,实际应用中根据掌握情况作出取舍,本文讨论 ...

  6. Linux学习之文件操作

    Linux,一起学习进步-    mkdir The mkdir command is used to create directories.It works like this: mkdir命令是用 ...

  7. html5 与视频

    1.视频支持格式. 有3种视频格式被浏览器广泛支持:.ogg,.mp4,.webm. Theora+Vorbis=.ogg  (Theora:视频编码器,Vorbis:音频编码器) H.264+$$$ ...

  8. 个人网站对xss跨站脚本攻击(重点是富文本编辑器情况)和sql注入攻击的防范

    昨天本博客受到了xss跨站脚本注入攻击,3分钟攻陷--其实攻击者进攻的手法很简单,没啥技术含量.只能感叹自己之前竟然完全没防范. 这是数据库里留下的一些记录.最后那人弄了一个无限循环弹出框的脚本,估计 ...

  9. 小兔JS教程(三)-- 彻底攻略JS回调函数

    这一讲来谈谈回调函数. 其实一句话就能概括这个东西: 回调函数就是把一个函数当做参数,传入另一个函数中.传进去的目的仅仅是为了在某个时刻去执行它. 如果不执行,那么你传一个函数进去干嘛呢? 就比如说对 ...

  10. continue break 区别

    在循环中有两种循环方式 continue , break continue 只是跳出本次循环, 不在继续往下走, 还是开始下一次循环 break  将会跳出整个循环, 此循环将会被终止 count = ...