我有一段使用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上尝试过什么,都抛出了相同的异常。
答案 0 :(得分:1)
System.Net.Http.HttpClient,System.Net.Http.HttpClientHandler和System.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
System.Net.Http
一个有点不同。使用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
以允许互联网访问。
希望这会有所帮助。祝你好运!