Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception calling PutAsJsonAsync from Xamarin

I am trying to write a small test application using WebApi. I have it mostly working, I am able to get data from my web service and display it in Android.

I added a button, and used the same code that I had used in my Winforms test client:

   async void buttonSave_Clicked(object sender, EventArgs e)
    {
        HttpClient client = new HttpClient ();
        Customer data = new Customer () {
        Surname = editSurname.Text,
        GivenName = editGivenName.Text};

        var result = await client.PutAsJsonAsync("http://10.0.0.4/WebApplication1/api/Customers/2", data);
       if (result.IsSuccessStatusCode ) {
       labelStatus.Text = "Saved";
       }
    }

This works fine in the Windows Forms test app, but in the Xamarin app I get an exception on client.PutAsJsonAsync:

E/mono-rt ( 7519): [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'System.Net.Http.ObjectContent`1[T]' from assembly 'System.Net.Http.Formatting, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Any suggestions? Using Xamarin 3.

edit:

It works if I format the content manually:

        string sData =   Newtonsoft.Json.JsonConvert.SerializeObject(data);

        HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,  "application/json") ;
        var result = await client.PutAsync("http://10.0.0.4/WebApplication1/api/Customers/2",content);

I have all the references correct, as far as I can see. I used the WebApi Client nuget package.

References:

Newtonsoft.Json
System.Net.Http
System.Net.Http.Extensions
System.Net.Http.Formatting
System.Net.Http.Primitives
like image 847
Molloch Avatar asked Jun 15 '14 22:06

Molloch


2 Answers

You need to install the following Nuget packages to all the projects that reference your HttpClient project

  1. Microsoft.Bcl.Build
  2. Microsoft.Bcl

These are the warnings from Visual Studio when I built my project and after I done that, it worked!

like image 160
Khang Tran Avatar answered Nov 07 '22 01:11

Khang Tran


Serialize your data into a JSON string like this:

  string json = JsonConvert.SerializeObject(item);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = null;
                    response = await client.PostAsync(url, content);
like image 36
Niek Vandael Avatar answered Nov 07 '22 00:11

Niek Vandael