天道酬勤,学无止境

"Operation is not valid" error at Xamarin.iOS project with HttpClient

I create HttpClient and call GetStringAsync method right at the button click handler:

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

And every time I get the following error:

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).

I'm not using portable libs, nugets, etc. Just plain project created from a template. How to solve this issue?

test project with reproduced issue here: https://dl.dropboxusercontent.com/u/19503836/HelloWorld3.zip

评论

In general this happens when you're building your application using PCL assemblies and from Windows.

I'm not using portable libs,

Ok, still you're likely falling into the same situation. You have the wrong (MS not XI) version of System.Http.Net.dll being copied (and compiled) on the Mac. E.g.

at System.Lightup....

Is not part of the assembly being shipped with Xamarin.iOS. Having this in your stack trace is an indication that the wrong assembly is being used.

This is a known issue that is being fixed (at least for the PCL part). In the mean time the general workaround is using a redirect file (see James blog) or build from the Mac.

In your specific case you might just need to ensure the right assembly is being referenced.

i had the same problem! resolve with FlorianZimmermann solution.

on this link: https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec

  1. right-click on References directory for ios or android solution
  2. select edit references
  3. in packages tab , check System.Net.Http
  4. build!

Hope it's help.

Another workaround would be to wrap up your web request in a service that gets injected into the PCL. Not ideal but thats what Im doing for now.

Before getting into major complications with platform specific "simple" handlers and IoC magic, I suggest you validate a couple of things. After all the whole point of Xamarin and Mono are to avoid all these black santeria hacks to begin with.

If this doesn't work, I would then science the shit of it, and go ballistic... but start here first:

  1. Make sure your platform specific project (MyProject.iOS, or MyProject.Android) HAVE the System.Net.Http referenced under references

  2. Make sure your PCL is targeting the a Profile that is supported by your platform specific project targets (as of the time of this writing, I use "PCL 4.5 - Profile78" with iOS and Android projects)

Good luck!

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 忽略Xamarin.Forms(PCL)中的SSL证书错误(Ignore SSL certificate errors in Xamarin.Forms (PCL))
    问题 有什么方法可以执行此处描述的操作:https://stackoverflow.com/a/2675183,但在Xamarin.Forms PCL App中? 我正在使用HttpClient连接到服务器。 回答1 ServicePointManager不是在PCL中定义的,而是在平台特定的类中定义的。 Xamarin.iOS和Xamarin.Android中都有ServicePointManager ,它们的用法相同。 您可以在平台项目的任何类中引用它。 但是,当前没有此类,对于Windows Phone应用程序似乎没有办法。 例子: // Xamarin.Android public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { // You may use ServicePointManager here ServicePointManager .ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; base.OnCreate
  • Xamarin 中使用 TLS 1.2 的 Https(Https with TLS 1.2 in Xamarin)
    问题 我在 Xamarin 中使用 HttpClient 向带有 TLS 1.2 的 https 请求,但出现如下错误; System.AggregateException: One or more errors occurred ---> System.Net.WebException: Error writing headers ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed. at Mono.Security.Protocol.Tls.RecordProtocol.ProcessAlert (AlertLevel alertLevel, AlertDescription alertDesc) [0x00013] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.9.1.3/src/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs:574 at
  • Error: ConnectFailure (Connection refused)
    I have the xamarin.forms application for which i am trying to connect localhost from PC to Iphone simulator in mac,Iam using the Ip address for connecting, private string Uri = "http://192.168.0.16:62271/";//Windows Ip address:localhost port number private string GetDishesUrl = "api/DishDetails/GetDishDetails?id=5"; try{ var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(Uri); var response = await httpClient.GetAsync(new Uri(Uri + GetDishesUrl)); var stringAsync = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var responseJson = stringAsync
  • Why do I get a NullReferenceException when creating an Instance of System.Net.Http.HttpClient()?
    In our Xamarin Forms App we have to load much data from multiple API´s. The easiest way is to use HttpClient directly fro the PCL, but I get this Error when there are several hundreds of them. With this Page I could reproduce this issue in a fresh PCL Project. using System; using Xamarin.Forms; namespace HTTPTest { public class HTTPTestPage : ContentPage { int Index = 0; public HTTPTestPage() { Content = new Label { Text = "HTTP Test" }; } protected override void OnAppearing() { base.OnAppearing(); StartLoading(); } void StartLoading() { for (int i = 0; i < 400; i++) { if (string.IsNullOrEmpty
  • System.MissingMethodException Method 'System.Net.Http.HttpClientHandler.set_Proxy' not found
    This is a Xamarin solution and I am getting the error found in this message's title. Of course, I can easily confirm that there is a Proxy property on HttpClientHandler in the PCL project. And the solution builds without error. Only when I run does it produce this error (on either Droid or iOS) and does so at the point where it invokes the method in the PCL which instantiates the HttpClient. Note that it doesn't even get to that method. The error appears on the application start-up method; e.g., UIApplication.Main() If I comment out the handler and instantiate HttpClient without a handler, it
  • 找不到 System.MissingMethodException 方法“System.Net.Http.HttpClientHandler.set_Proxy”(System.MissingMethodException Method 'System.Net.Http.HttpClientHandler.set_Proxy' not found)
    问题 这是一个 Xamarin 解决方案,我在此消息的标题中发现了错误。 当然,我可以轻松确认PCL项目中HttpClientHandler上有Proxy属性。 并且解决方案构建没有错误。 只有当我运行时它才会产生这个错误(在 Droid 或 iOS 上),并且在它调用 PCL 中实例化 HttpClient 的方法时会产生这个错误。 请注意,它甚至没有达到该方法。 错误出现在应用程序启动方法上; 例如,UIApplication.Main() 如果我注释掉处理程序并在没有处理程序的情况下实例化 HttpClient,只要我在开放的互联网上,它就可以正常工作。 但我试图让它从代理后面工作。 进一步调查表明,设备项目没有对 System.Net.Http 的引用。 所以我添加了这些——它表明 Xamarin.iOS 和 Xamarin.Android 作为包——但它仍然产生错误。 我不清楚错误告诉我什么,但我相信这意味着设备项目看不到 System.Net.Http.HttpClientHandler? private HttpClient GetHttpClient() { WebProxy proxy = new WebProxy(ProxyConfig.Url) { Credentials = new NetworkCredential(ProxyConfig.Username
  • Xamarin iOS HttpClient Timeout doesn't work
    At some point we found all the requests in our app have timeout of 60 seconds on iOS though we set the default value for the HTTP framework we use as 3 minutes. I tried the following piece of code to figure out if it's the library who has an issue: try { using (var http = new HttpClient()) { http.Timeout = TimeSpan.FromMinutes(1.5); await http.GetAsync("https://httpstat.us/200?sleep=70000"); } } catch (Exception ex) { } This code fails with the timeout exception though the timeout is set as 90 sec and the request goes for 70 sec. Turns out it doesn't override the default timeout of 60 sec. The
  • UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread
    I'm trying to run this code: GetRepsButton.Command = new Command(async () => { var url = @"https://url"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //crashes here var test = await client.GetStringAsync(url); }); And when I do, the entire app crashes and the output window shows this error: ROR: +[MSWrapperLogger MSWrapperLog:tag:level:]/7 Unhandled Exception: UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread. at UIKit
  • Https with TLS 1.2 in Xamarin
    I'm using HttpClient in Xamarin to request to https with TLS 1.2 and I got the error as below; System.AggregateException: One or more errors occurred ---> System.Net.WebException: Error writing headers ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed. at Mono.Security.Protocol.Tls.RecordProtocol.ProcessAlert (AlertLevel alertLevel, AlertDescription alertDesc) [0x00013] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.9.1.3/src/mono/mcs/class/Mono.Security/Mono.Security
  • Xamarin.iOS Operation is not supported on this platform Exception at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDynamicMethod
    I'm working on a cross-platform project with Xamarin.Forms. In my project, I'm using an API to login by a username and password. When I try to login on Android and UWP platorms, it works perfectly. But when I want to login in my iOS project, It throws an exception that says: System.PlatformNotSupportedException: Operation is not supported on this platform. The Exception is thrown on this line of my code: HttpContent content = new FormUrlEncodedContent(keyValuePairs); HttpResponseMessage response = await httpClient.PostAsync("token", content); Here is the full StackTrace: at System.Reflection
  • 此平台不支持 Xamarin.iOS 操作 Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDynamicMethod 处的异常(Xamarin.iOS Operation is not supported on this platform Exception at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDynamicMethod)
    问题 我正在使用 Xamarin.Forms 进行跨平台项目。 在我的项目中,我使用 API 通过用户名和密码登录。 当我尝试在 Android 和 UWP 平台上登录时,它运行良好。 但是当我想登录我的 iOS 项目时,它抛出一个异常,说: System.PlatformNotSupportedException:此平台不支持操作。 在我的代码的这一行上抛出异常: HttpContent content = new FormUrlEncodedContent(keyValuePairs); HttpResponseMessage response = await httpClient.PostAsync("token", content); 这是完整的 StackTrace: 在 System.Reflection.Emit.DynamicMethod..ctor (System.String name, System.Type returnType, System.Type[] parameterTypes, System.Type owner, System.Boolean skipVisibility) [0x00006] in /Library/Frameworks/Xamarin。 iOS.framework/Versions/12.2.1.11/src/Xamarin
  • 我现在应该如何使用带有 PCL 或不带 PCL 的 Azure 移动服务?(How should i use Azure Mobile Services with PCL or without it now?)
    问题 我更新到最新版本的 Xamarin,其中“完全支持”PCL。 我现在如何使用 Azure 移动服务? 如果我创建 PCL 库并尝试使用 NuGet 添加它,则无法安装“Newtonsoft.Json 5.0.8”,因为它需要缺少“portable-net45+wp80+MonoAndroid10+MonoTouch10”。 如果我创建简单的 android lib 并从组件中添加 Azure,它会生成异常: System.InvalidOperationException:未找到当前平台的 Windows Azure 移动服务程序集。 确保当前… 在 public static MobileServiceClient MobileService = new MobileServiceClient( "https://no-link-here.azure-mobile.net/", "no-key-here"); 回答1 首先,请确保您使用的是 NuGet 或 Xamarin 组件的 1.1.5 或更高版本,因为以前的版本在 PCL 支持方面存在一些问题。 有关在 PCL 中使用移动服务的分步指南,请参阅本教程。 如果你将 Xamarin 组件或 Azure 移动服务的 NuGet 包安装到你的 Android 应用程序中,你会发现它添加了这些引用(以及其他): 微软
  • 为什么在创建 System.Net.Http.HttpClient() 的实例时会出现 NullReferenceException?(Why do I get a NullReferenceException when creating an Instance of System.Net.Http.HttpClient()?)
    问题 在我们的 Xamarin Forms 应用程序中,我们必须从多个 API 加载大量数据。 最简单的方法是直接从 PCL 使用 HttpClient,但是当有数百个时我会收到此错误。 有了这个页面,我可以在一个新的 PCL 项目中重现这个问题。 using System; using Xamarin.Forms; namespace HTTPTest { public class HTTPTestPage : ContentPage { int Index = 0; public HTTPTestPage() { Content = new Label { Text = "HTTP Test" }; } protected override void OnAppearing() { base.OnAppearing(); StartLoading(); } void StartLoading() { for (int i = 0; i < 400; i++) { if (string.IsNullOrEmpty(LoadStringFromEndpoint("https://google.de"))) { break; } } } public string LoadStringFromEndpoint(string url) { System.Diagnostics
  • System.Net.WebClient异常缓慢(System.Net.WebClient unreasonably slow)
    问题 当使用System.Net.WebClient.DownloadData()方法时,响应时间变得异常缓慢。 使用.NET中的WebClient类获取URL时,大约需要10秒才能收到响应,而我的浏览器将在1秒内获取同一页面。 而这是0.5kB或更小的数据。 该请求包含POST / GET参数和一个用户代理标头(如果可能会引起问题)。 我尚未尝试过.NET中其他下载数据的方式是否也给我带来了同样的问题,但是我怀疑可能会得到类似的结果。 (我一直觉得.NET中的Web请求异常缓慢...) 这可能是什么原因? 编辑: 我尝试使用System.Net.HttpWebRequest来执行确切的操作,而是使用以下方法,并且所有请求在1秒内完成。 public static string DownloadText(string url) var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } 尽管使用System.Net
  • Json DeserializeObject throws exception only by iOS
    I don't have this problem by Android, but when I run the same working code in iOS then I get exception public async Task Login(string inlogData, string password, string gcm) { Login login = new Dharma.Login (); login.inlog_data = inlogData; login.password = password; login.phone_token = gcm; HttpClient client = new HttpClient (); HttpResponseMessage response = null; string json = JsonConvert.SerializeObject(login, Formatting.Indented); client.Timeout = TimeSpan.FromMilliseconds (10000); client.BaseAddress = new Uri (ConstantVariabels.GetLoginUrl()); client.DefaultRequestHeaders.Accept.Add(new
  • 在Xamarin中创建PCL时,.Net可移植子集缺少HttpClient(HttpClient missing from .Net portable subset while creating PCL in Xamarin)
    问题 我已经在Xamarin中创建了可移植类库,并希望将其用于android应用。 我想在此PCL中使用HttpClient 。 我已经从NuGet软件包管理器中添加了Microsoft Http Client libraries 。 现在,我可以看到.Net portable subset添加到我的引用中。 但是我仍然不能以某种方式使用HttpClient ,它也不会显示在.Net可移植子集中。 另外,我的PCL Current profile是4.0-Profile 158 。 如果我将配置文件更改为4.5,则Xamarin崩溃且无法打开解决方案 谁能帮我这个? 谢谢 回答1 简单的解决方案是针对.NET 4.5,Windows应用商店应用程序(Windows 8.1),Xamarin.iOS和Xamarin.Android(4.5-Profile7)。 然后,您将不需要HttpClient NuGet包来获取这些API。 如果您在尝试选择4.5配置文件时Xamarin崩溃,请确保您使用的是最新版本,然后报告该错误以及有关如何对其进行复制以及发生什么情况的详细信息。 此外,HttpClient NuGet软件包还应允许您使用PCL配置文件158中的HttpClient。确保您使用的是最新版本的NuGet。 “ .NET便携式子集”应该始终出现在PCL的引用中,与NuGet包无关
  • Xamarin.iOS Can't compile project "app was built for iOS 10.2 which is newer than this simulator"
    I'm working with Xamarin.iOS, right now I'm doing some test with a library(from GitHub) that provides some Material UI elements, it already have a Xamarin binding and some samples, the problem is that I can't compile the samples project. I get the following error: dyld: app was built for iOS 10.2 which is newer than this simulator 10.1 /Users/user/Projects/MaterialControls.Xamarin.Sample/iOS/LaunchScreen.storyboard: Error: dyld: app was built for iOS 10.2 which is newer than this simulator 10.1 2017-03-10 11:57:49.396 ibtoold[3878:537684] [MT] DVTAssertions: Warning in /Library/Caches/com
  • Xamarin.Forms IOS error replacing existing signature
    I think this error started happening after I change the provisioning profile. My app is on visual 2017 Xamarin.Forms project and building through on Windows PC connected to a MAC book. The Android and UWP projects works fine. I have tried: uninstalling / reinstalling skiasharp package uninstalling Xamarin.IOS with the uninstall script and emptying the cache folder on the MAC side Allow full access to the keychains to all applications Here is the error: /Users/myusername/Library/Caches/Xamarin/mtbs/buildsenter code here/MyAppName.iOS/ec3fa8c87274cfb85c8423bb8f475608/bin/iPhone/Debug/MyAppName
  • Xamarin.iOS 无法编译项目“应用程序是为比此模拟器更新的 iOS 10.2 构建的”(Xamarin.iOS Can't compile project "app was built for iOS 10.2 which is newer than this simulator")
    问题 我正在使用 Xamarin.iOS,现在我正在使用提供一些 Material UI 元素的库(来自 GitHub)进行一些测试,它已经有一个 Xamarin 绑定和一些示例,问题是我无法编译示例项目。 我收到以下错误: dyld:应用程序是为 iOS 10.2 构建的,它比这个模拟器 10.1 更新 /Users/user/Projects/MaterialControls.Xamarin.Sample/iOS/LaunchScreen.storyboard:错误:dyld:应用程序是为 iOS 10.2 构建的,它比这个模拟器 10.1 2017-03-10 11:57:49.396 ibtoold[3878: 537684] [MT] DVTAssertions:警告 /Library/Caches/com.apple.xbs/Sources/IDEInterfaceBuilder/IDEInterfaceBuilder-11762/InterfaceBuilderKit/Utilities/IBAbstractInterfaceBuilderPlatformToolManager.m:254 详细信息:无法附加到 Interface Builder Cocoa Touch Tool 错误:Error Domain=com.apple.InterfaceBuilder
  • Xamarin.Forms IOS 错误替换现有签名(Xamarin.Forms IOS error replacing existing signature)
    问题 我认为在更改配置文件后开始发生此错误。 我的应用程序在 Visual 2017 Xamarin.Forms 项目上,并在连接到 MAC 书籍的 Windows PC 上构建。 Android 和 UWP 项目运行良好。 我努力了: 卸载/重新安装skiasharp 软件包使用卸载脚本卸载 Xamarin.IOS 并清空 MAC 端的缓存文件夹允许对所有应用程序的钥匙串进行完全访问 这是错误: /Users/myusername/Library/Caches/Xamarin/mtbs/buildsenter code here/MyAppName.iOS/ec3fa8c87274cfb85c8423bb8f475608/bin/iPhone/Debug/MyAppName.iOS.app/Frameworks/libSkiaSharp.framework/libSkiasharp.framework/libSkiasignature/libSkia /Library/Caches/Xamarin/mtbs/builds/MyAppName.iOS/ec3fa8c87274cfb85c8423bb8f475608/bin/iPhone/Debug/MyAppName.iOS.app/Frameworks/libSkiaSharp.framework/libSkiaSharp