Using HttpContext.Current in WebApi is dangerous because of async

HttpContext.Current gets the current context by Thread (I looked into the implementation directly). 提问中的描述

It would be more correct to say that HttpContext is applied to a thread; or a thread "enters" the HttpContext.

Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread.  提问中的描述

Not at all; the default behavior of async/await will resume on an arbitrary thread, but that thread will enter the request context before resuming your async method.


The key to this is the SynchronizationContext. I have an MSDN article on the subject if you're not familiar with it. A SynchronizationContext defines a "context" for a platform, with the common ones being UI contexts (WPF, WinPhone, WinForms, etc), the thread pool context, and the ASP.NET request context.

The ASP.NET request context manages HttpContext.Current as well as a few other things such as culture and security. The UI contexts are all tightly associated with a single thread (the UI thread), but the ASP.NET request context is not tied to a specific thread. It will, however, only allow one thread in the request context at a time.

The other part of the solution is how async and await work. I have an async intro on my blog that describes their behavior. In summary, await by default will capture the current context (which is SynchronizationContext.Current unless it is null), and use that context to resume the async method. So, await is automatically capturing the ASP.NET SynchronizationContext and will resume the async method within that request context (thus preserving culture, security, and HttpContext.Current).

If you await ConfigureAwait(false), then you're explicitly telling await to not capture the context.

Note that ASP.NET did have to change its SynchronizationContext to work cleanly with async/await. You have to ensure that the application is compiled against .NET 4.5 and also explicitly targets 4.5 in its web.config; this is the default for new ASP.NET 4.5 projects but must be explicitly set if you upgraded an existing project from ASP.NET 4.0 or earlier.

You can ensure these settings are correct by executing your application against .NET 4.5 and observing SynchronizationContext.Current. If it is AspNetSynchronizationContext, then you're good; if it's LegacyAspNetSynchronizationContext, then the settings are wrong.

As long as the settings are correct (and you are using the ASP.NET 4.5 AspNetSynchronizationContext), then you can safely use HttpContext.Current after an await without worrying about it.

HttpContext.Current and Web Api的更多相关文章

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

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

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

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

  3. HttpContext为null new HttpContextWrapper(System.Web.HttpContext.Current)

    HttpContext = (context == null ? new HttpContextWrapper(System.Web.HttpContext.Current) : context);

  4. System.Web.HttpContext.Current.Server.MapPath("~/upload/SH") 未将对象引用设置为实例对象

    做项目的时候,System.Web.HttpContext.Current.Server.MapPath("~/upload/SH")   获取路径本来这个方法用的好好的 因为需要 ...

  5. System.Web.HttpContext.Current.Session获取值出错

    在自定义类库CS文件里使用System.Web.HttpContext.Current.Session获取Session时提示错误:未将对象引用设置到对象的实例. 一般情况下通过这种方式获取Sessi ...

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

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

  7. .NET System.Web.HttpContext.Current.Request报索引超出数组界限。

    移动端使用Dio发送 FormData, 请求类型 multipart/form-data, FormData内可以一个或多个包含文件时. 请求接口时获取上传的fomdata数据使用 System.W ...

  8. System.Web.HttpContext.Current.Request用法

    public static void SetRegisterSource() { if (System.Web.HttpContext.Current.Request["website&qu ...

  9. 慎用System.Web.HttpContext.Current

    每当控制流离开页面派生的Web表单上的代码的时候,HttpContext类的静态属性Current可能是有用的. 使用这个属性,我们可以获取当前请求(Request),响应(Response),会话( ...

随机推荐

  1. PostgreSQL远程代码执行漏洞(CVE-2018-1058)学习笔记

    零.参考文献和绪论: 1.先知社区chybeta大神的--PostgreSQL 远程代码执行漏洞分析及利用—[CVE-2018-1058]--一文 2.博客园hunchill的--Mac 下 Post ...

  2. window自带字体

    一.在默认情况下, Windows 默认提供下列字体: Windows 95/98/98SE 宋体.黑体.楷体_GB2312.仿宋_GB2312 Windows XP/2000/2003/ME/NT ...

  3. 1.border-image

    1.设置在元素围绕的border的图片,用图片代替边框 语法: broder-image-source:图片 border-image-slice:切下的区域,数字|百分比(相对于图像的高度和宽度) ...

  4. tomcat配置JMX

    最近看JDK的命令行工具,使用Java VisualVM和Jconsole工具都可以监控java程序的运行情况(包括CUP和内存等的使用情况,线程的运行状态等) 在Java VisualVM 工具里可 ...

  5. ThinkPHP如果表名有下划线需要用Model应该怎么做?

    最近遇到一个问题,在用TP做系统的时候,我建立的表是 “tp_admin_user” 但是要用到的模型是 “AdminUserModel.model.class.php”,应该如何做? 解决方法: & ...

  6. 用到了yii2 hasMany() 方法,一对多关联

    view页面代码:其中supply,item,price是一个AR类都是一个类,item和prices是一对多关系: [ 'label' => '参考', 'format' => 'htm ...

  7. 安装MySQL与安装Hive

    安装mysql 检查是否安装mysql: rpm -qa |grep mysql 删除已经安装的mysql: rpm -e mysql-libs-5.1.71-1.el6.x86_64 报错:因为my ...

  8. opencv学习笔记——颜色空间转换函数cv::cvtColor详解

    cv::cvtColor()用于将图像从一个颜色空间转换到另一个颜色空间的转换(目前常见的颜色空间均支持),并且在转换的过程中能够保证数据的类型不变,即转换后的图像的数据类型和位深与源图像一致. 具体 ...

  9. JSON_CONTAINS

    select * from tb    where info->'$.name' = '特价促销'  or JSON_CONTAINS(info->'$[*].name', '" ...

  10. Python量化教程 常用函数

    # -*- coding: utf-8 -*- # @Author: fangbei # @Date: 2017-08-26 # @Original: price_str = '30.14, 29.5 ...