HttpContext.Current is null after await completed

2019-06-21 05:31发布

问题:

I have the following simple WCF service defined in .NET 4.5 web app:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet(UriTemplate = "json/DoWork/", ResponseFormat = WebMessageFormat.Json)]
    Task<string> DoWork();
}

public class Service1 : IService1
{
    public async Task<string> DoWork()
    {
        Debug.WriteLine(HttpContext.Current != null);
        var s = await new HttpClient().GetStringAsync("http://www.google.com");
        Debug.WriteLine(HttpContext.Current != null);
        return s;
    }
}

And the web.config is:

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

  <system.serviceModel>
    <services>
      <service name="WebApplication1.Service1">
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="WebApplication1.IService1"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="">
          <webHttp />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true"
                           httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
                               multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>

The output is

True
False

Shouldn't the context be available after await completed in .NET 4.5?