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
You need to install the following Nuget packages to all the projects that reference your HttpClient project
These are the warnings from Visual Studio when I built my project and after I done that, it worked!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With