Search code examples
iosxamarin.formshttpclient

Xamarin Forms HttpClient PostAsync always throw NSMallocException


We are building a mobile app for iOS and Android using Xamarin Forms 5 and using Visual Studio 2022. When we make a Post request to any api, both our own as external api's we are always returned:

Xamarin.PreBuilt.iOS[3728:2199180] Xamarin.iOS: Received unhandled ObjectiveC exception: NSMallocException Failed to grow buffer

GET request work fine. I have searched Google and StackOverflow but can not find any help. I have tried to increase the HttpClient.MaxResponseContentBufferSize without any difference.

The app for now is very simple, one page with a button to test. Code behind is as followed:

public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri("https://ptsv2.com/");

            string jsonData = @"{}";

            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("/t/l4x2e-1637576441/post", content);

            var result = await response.Content.ReadAsStringAsync();
        }
    } 

This fails on iOS linked device, but for Android Simulator it works. Is there anything I need to change for iOS?

Update

The code works on multiple machines except mine, trying to figure out what setting this could be, any ideas would be greatly appreciated.


Solution

  • I've had exactly the same problem, and have logged a ticket with Microsoft on the VS feedback forums. And then today I found a simple work-around. At least I assume it's a work-around and not a solution. Where I had

    HttpClient client = new HttpClient() 
    

    I instead do this:

    var handler = new HttpClientHandler();
    HttpClient client = new HttpClient(handler);
    

    And bingo, it now works.