2

I have a piece of code that uses System.Net.Http Library. and when ever I create new instance of System.Net.Http.HttpClientHandler an Exception occures , For Example:

    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;
    }

and the Exception is :

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

I tested the code on win 7, no exception thrown, but whatever i tried on win8.1 the same exception was thrown.

0

1 Answer 1

1

The System.Net.Http.HttpClient, System.Net.Http.HttpClientHandler and System.Net.Http.HttpResponseMessage implements the IDisposable interface, and should be disposed; typically you would put them in using blocks.

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;
       }
    }
}

Anyway... I don't think this will solve your problem :P

  1. I think you are using VS2015 RC, this appears to be a common issue on that version.
  2. However, it is recommended for Windows 8.1 WinRT to use the Windows.Web.Http.HttpClient, which works a little bit different than System.Net.Http one.

Using the Windows.Web.Http namespace:

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;
          }
      }
}

Last, you have set the Capabilities in the Package.appxmanifest to allow Internet access.

Hope this helps. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.