For the life of me, I cannot understand why Transport Layer Security (TLS) 1.2 is not yet supported out of the box for Xamarin. According to Xamarin’s website, this is due to the fact that Mono still only supports TLS 1.0.
Xamarin has provided special handler’s that will leverage platform specific API’s that enable TLS 1.2; unfortunately, these handlers are not Portable Class Library (PCL) friendly and support only the most recent platform operating systems. I don’t know about you, but the mobile apps that I develop can’t be that picky in respect to the devices I support. I wish I only had to support the latest and greatest :p.
Fortunately, there is a simple solution that is both PCL friendly and can support older OS’s. This means that we can use this within a Xamarin.Forms solution.
- Right click packages (in the solution explorer)
- Click Add Packages…
- Search “ModernHttpClient”
- Find the following package: Id = modernhttpclient, Author = Paul Betts
- Add the package to EACH project package folder (PCL, Android, iOS,…)
// NOTE: ModernHttpClient has to be installed within each project due to how bait-and-switch libraries work.
Next, add the following packages to the PCL project:
- Id = Microsoft.Bcl, Author = Microsoft
- Id = Microsoft.Bcl.Build, Author = Microsoft
- Id = Microsoft.Net.Http, Author = Microsoft
You are now ready to start writing REST code. The secret behind ModernHttpClient is that it will use a bait-and-switch technique that will utilize the native platform handlers that support TLS 1.2. Simply use the following message handler: NativeMessageHandler().
Below is a rudimentary code sample without error handling (within the PCL):