Jared Price Jared Price - 9 months ago 77
iOS Question

C# - Xamarin - HttpClient - Operation is not valid due to the current state of the object - iOS

I'm working on a cross platform library that makes HTTP requests. It's working fine on Android, but when I try to use it on iOS I'm getting an exception and I can't figure out how to fix it.

Here is my code:

// method from cross platform library

var client = new HttpClient();
// some other setup stuff
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.post, "http://myurl.com...");

var task = client.SendAsync(request);
task.Wait(); // Exception thrown on this line

var response = task.Result;

var responseString = response.Content.ReadAsStringAsync().Result;
catch (Exception e)

I get a
with an inner exception of
that says
Operation is invalid due to the current state of the object.

Trying to find some solutions, I found that the issue could be cause by calling this on the UI thread. But that's the whole point of wrapping this all in

I've tried everything I know to do and have yet to solve the issue. Any help would be very appreciated.


I decided to try my solution on an iPhone simulator. It's an iPhone 6 simulator running iOS 10. My physical device is the same. It works on the simulator, but not the physical device for some reason... very strange.

Edit 2:

Thanks to @YuriS for finding a solution.

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

What you can do is:
1) Go to References of ios Project
2) Edit References
3) Check 'System.Net.Http'

Behaviour for android is the same.

Answer Source

There can be few problems described here: https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec


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


Seems all post pointing on System.Net.Http

Regardless of the problem there is a better ways doing this.One of them:

public static async Task PostRequest()
        HttpClient client = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://myuri");
        //request.Headers.Add("", "");
        var response = await client.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();
    catch (Exception ex)


If you want to wait till function completes you call

await PostRequest();

If you don't need to wait then just omit "await" in the call or use


Also you need to handle an exception within the function, so probably returning just Task is not the best. I was just basing my answer on original function signature