Wednesday, October 21, 2015

HTTP Client PostAsync Fails in MonoTouch/iPhone

Problem:
Running tests on our cross platform solution and encountered an issue. 

I get an exception thrown on my call to postasjsonasync(). The exception says "A type load exception occured"

One step in our app sends an email out of the app using the HTTPClient libraries from MS.  This is known to cause issues.  I hit the boards stackoverflow, Xamarin, etc..  This is a fairly common problem.  The crazy thing is that we are using this call in our pcl. It works with no issues on Android and Windows Phone.  It is a problem on iOS.  It appears to be a mapping issue in the PCL.

Solution:
James Montemagno did come up with a solution. The issue with the error was assembly binding error.  The iOS version was binding to the native Windows System.Net.Http for .Net 4.5. 

We should be binding to the Xamarin version which is at

C:\Program Files(x86)\Reference Assemblies\Microsoft\Framework\Xamain.iOS\v1.0

Why?
"The reason for the redirect is that the Microsoft.Net.HttpClient packages contains the System.Net.HttpClient namespace but that already exists on iOS and Android (with slightly different features even). At runtime it will resolve to the wrong assembly and not use the (Xamarin-)native iOS one." (Thanks James!)


You can fix this problem by modifying the app.config in the Touch project.
 
    <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>



Source:
http://stackoverflow.com/questions/27521738/httpclient-failing
https://github.com/Krumelur/HttpClientTest/blob/master/HttpClientTest_iOS/app.config

No comments:

Post a Comment