无法在Windows 8.1上实例化System.Net.Http.HttpClientHandler

时间:2015-07-18 16:56:20

标签: c# windows http windows-8.1

我有一段使用System.Net.Http库的代码。 当我创建System.Net.Http.HttpClientHandler的新实例时,会发生异常,例如:

    private async void btnTest_Click(object sender, RoutedEventArgs e)
    {
        var handler = new System.Net.Http.HttpClientHandler();
        //default constructor does the same thing :this(new HttpClientHandler())
        var client = new System.Net.Http.HttpClient(handler);
        var resp = (await client.GetAsync("any url"));
        var content = resp.Content;
    }

和例外是:

System.TypeLoadException: Could not load type
'System.Security.Authentication.SslProtocols' from assembly 
'System.Net.Primitives, Version=4.0.0.0, Culture=neutral, 
PublicKeyToken=b03f5f7f11d50a3a'.

   at System.Net.Http.HttpClientHandler..ctor()
   at MyApp.MainWindow.<btnTest_Click>d__0.MoveNext() in c:\MyApp\MainWindow.xaml.cs:line 30

我在win 7上测试了代码,没有抛出任何异常,但无论我在win8.1上尝试过什么,都抛出了相同的异常。

1 个答案:

答案 0 :(得分:1)

System.Net.Http.HttpClientSystem.Net.Http.HttpClientHandlerSystem.Net.Http.HttpResponseMessage实现了IDisposable接口,应予以处置;通常你会将它们放在using块中。

using(var handler = new System.Net.Http.HttpClientHandler())
{ 
    using(var client = new System.Net.Http.HttpClient(handler))
    {
       using(var resp = (await client.GetAsync("any url")))
       {
            var content = resp.Content;
       }
    }
}

无论如何......我认为这不会解决你的问题:P

  1. 我认为您使用的是VS2015 RC,这似乎是该版本的常见问题。
  2. 但是,建议Windows 8.1 WinRT使用Windows.Web.Http.HttpClient,它与System.Net.Http一个有点不同。
  3. 使用Windows.Web.Http命名空间:

    using (Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter())
    {
         using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(filter))
         {
              using (Windows.Web.Http.HttpResponseMessage resp = await client.GetAsync(new Uri("Any Uri")))
              {
                   var content = resp.Content;
              }
          }
    }
    

    最后,您已在Capabilities中设置Package.appxmanifest以允许互联网访问。

    希望这会有所帮助。祝你好运!