使用HttpClient在Xamarin.iOS项目中"操作无效"错误

Ale*_*akh 6 httpclient xamarin.ios xamarin

我创建HttpClient并在按钮单击处理程序上调用GetStringAsync方法:

var client = new HttpClient();
var response = await client.GetStringAsync("http://google.com");
Debug.WriteLine("Response received: {0}", response);
Run Code Online (Sandbox Code Playgroud)

每次我收到以下错误:

System.InvalidOperationException: Operation is not valid due to the current state of the object

2014-05-10 01:26:36.657 HelloWorld3[490:60b] Unhandled managed exception: Operation is not valid due to the current state of the object (System.InvalidOperationException)
  at System.Lightup.Call[HttpWebRequest,Int64] (System.Delegate& storage, System.Net.HttpWebRequest instance, System.String methodName, Int64 parameter) [0x00000] in <filename unknown>:0 
  at System.Lightup.Set[HttpWebRequest,Int64] (System.Delegate& storage, System.Net.HttpWebRequest instance, System.String propertyName, Int64 value) [0x00000] in <filename unknown>:0 
  at System.Net.HttpWebRequestLightup.SetContentLength (System.Net.HttpWebRequest instance, Int64 value) [0x00000] in <filename unknown>:0 
  at System.Net.Http.HttpWebRequest.set_ContentLength (Int64 value) [0x00000] in <filename unknown>:0 
  at System.Net.Http.HttpClientHandler.StartRequest (System.Object obj) [0x00000] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispat
chInfo.Throw () [0x0000b] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:62 
  at System.Runtime.CompilerServices.TaskAwaiter`1[System.String].GetResult () [0x00000] in <filename unknown>:0 
  at HelloWorld3.MyViewController+<<ViewDidLoad>b__0>d__1.MoveNext () [0x00029] in c:\Sources\Local\HelloWorld3\HelloWorld3\MyViewController.cs:41 
Debugging session ended.
The program 'Mono' has exited with code 0 (0x0).
Run Code Online (Sandbox Code Playgroud)

我没有使用便携式库,nugets等.只是从模板创建的普通项目.如何解决这个问题?

此处重现问题的测试项目:https: //dl.dropboxusercontent.com/u/19503836/HelloWorld3.zip

pou*_*pou 8

通常,当您使用PCL程序集 Windows 构建应用程序时会发生这种情况.

我没有使用便携式库,

好吧,你仍然可能陷入同样的​​境地.您System.Http.Net.dll在Mac上复制(和编译)了错误的(MS不是XI)版本.例如

在System.Lightup ....

不是Xamarin.iOS随附的组件的一部分.在堆栈跟踪中显示此信息表示正在使用错误的程序集.

这是一个已修复的已知问题(至少对于PCL部分而言).与此同时,一般的解决方法是使用重定向文件(请参阅James博客)或使用Mac构建.

在您的特定情况下,您可能只需要确保正在引用正确的程序集.