Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringContent is empty on Xamarin.Android

We have an Azure WebApi service that can sometimes return a BadRequest like so

return BadRequest("{\"errors\":[{\"message\":\"MyBuddy not found!\",\"code\":9}]}");

The problem is that on Xamarin.Android, using the System.Net.Http.HttpClient, the response content that we receive is empty.

This is our code:

private static async Task<int> ReadErrorCodeAsync(HttpResponseMessage response)
    {
        var x = response.ReasonPhrase;
        var errorSerialized = await response.Content.ReadAsStringAsync();
        var error = JObject.Parse(errorSerialized);

        return ((JArray)error["errors"])[0]["code"].Value<int>();
    }

But errorSerialized is always an empty string. We also use a Swagger UI and there the response content is what we expect, e.g.:

{
  "errors": [
    {
      "message": "MyBuddy not found!",
      "code": 9
    }
  ]
}

Is it normal that the Content of a BadRequest reponse is empty on Xamarin.Android? Is there anything I can do, e.g. configure the HttpClient differently, so that I receive the StringContent?

EDIT: we're using the AndroidClientHandler. For this we've added a text file to the Android project, set its BuildAction to AndroidResource and its content to XA_HTTP_CLIENT_HANDLER_TYPE=Xamarin.Android.Net.AndroidClientHandler

like image 416
Marius Muntean Avatar asked Aug 18 '16 06:08

Marius Muntean


1 Answers

This is a bug in the AndroidClientHandler. It isn't reading the error response properly. (see https://github.com/xamarin/xamarin-android/blob/master/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs#L308 )

I've fixed it. Let's hope they will merge it quickly :) https://github.com/xamarin/xamarin-android/pull/180

If you need to use it before Xamarin has merged and released it, you have to:

  • copy this folder in some folder in your android project
  • change the namespace in all files to Xamarin.Android.Net.Fix
  • delete or comment all Logger lines that cause compile errors
  • change the content of your environment file to XA_HTTP_CLIENT_HANDLER_TYPE=Xamarin.Android.Net.Fix.AndroidClientHandler,MyApp.Android (replace MyApp.Android with the assembly name of your Android app)
like image 110
Sven-Michael Stübe Avatar answered Oct 03 '22 04:10

Sven-Michael Stübe