System.Web.HttpContext.Current發生Null的情況

今天在使用.NET Framework 4.5版的IIS伺服器上,發現了一個超級詭異的情況,就是在進行某多執行緒(multi-threads)的非同步存取(async; asynchronous)時,某aspx / ashx竟然給我跳出一個Exception,意思上大致上是說,System.Web.HttpContext.Current不存在,也就是它是一個Null。看到訊息的當下心中只有WTF三個字,今天aspx / ashx不就是透過IIS進來執行的嗎?進來執行後你又跟我說沒有HttpContext.Current這算是哪招?

在網路上查到的原因,原來是.NET Framework 4.5開始針對非同步的調用(async / await)進行效能上的優化以及處理調用方式的修正,以下是原文的說明以及來源。

All about <httpRuntime targetFramework>

Enables the new await-friendly asynchronous pipeline that was introduced in 4.5. Many of our synchronization primitives in earlier versions of ASP.NET had bad behaviors, such as taking locks on public objects or violating API contracts. In fact, ASP.NET 4’s implementation of SynchronizationContext.Post is a blocking synchronous call! The new asynchronous pipeline strives to be more efficient while also following the expected contracts for its APIs. The new pipeline also performs a small amount of error checking on behalf of the developer, such as detecting unanticipated calls to async void methods.

解決方法

解決方法很簡單,基本上有兩種方式,都從web.config下手即可。

解決方法A:

<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

解決方法B:

<configuration>
  <system.web>
    <httpRuntime targetFramework="4.5" />

或者你A、B兩者都要寫在設定檔裡面也可以,並不衝突。Happy coding!

System.Web.HttpContext.Current System.Web.HttpContext.Current.Request.Url.Host null NullRefenence async/await