How to correct Null Reference Exception when using HttpClient with Xamarin and iOS

Problem:

When I use HttpClient in my Xamarin project it works with Android but throws a Null Reference exception on iOS.

Solution:

Add an app.config with the the following content:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="2.0.5.0" />
         </dependentAssembly>

      </assemblyBinding>
   </runtime>
</configuration>

Explanation:

The namespace for HttpClient exists on Android and iOS which conflicts with the one in System.Net.HttpClient. The redirect makes sure you find the correct version.

Comments (2) -

  • Viswanath Ivatury

    7/12/2018 5:18:41 AM | Reply

    Does this work with Xamarin forms? If so does it need to be added to iOS and Android projects or to PCL?

    • Donovan

      8/7/2018 8:42:08 PM | Reply

      Those are good questions. It was a Xamarin forms because that is pretty much all I do. But I can't find the project where I did this so I don't remember which project I added it to. I would guess the iOS project. Will have to try and let me know.

Add comment

Loading