Menu

Azure Mobile Apps comes with a great client SDK that creates a client connection on its own. In the .NET library, that’s provided by System.Net.Http.HttpClient. If you take a look at the Xamarin implementation of System.Net.Http.HttpClient (for example, for Android), you should note that it uses raw I/O to a TCP/IP socket – the underlying building block of all internet communication that dates way back to the origins of the Internet and TCP/IP.

So what, you might ask? Well, doing raw I/O may not be the best way of communicating with a backend on all platforms. Both iOS and Android contains in-built raw libraries for doing HTTP and they deal with the underlying OS libraries to be more efficient. In the Android case, that’s HttpUrlConnection and in the iOS case, that’s NSURLConnection. In addition, there are other libraries that offer improvements for simple operations. Your client may be doing other (non-Mobile Apps) operations for this.

Fortunately, there is an answer. Paul Betts has produced a nice client alternative as a Portable Class Library called modernhttpclient and it’s open-source. The Portable Class Library (or PCL) is important because it means it can run on Xamarin as well as Windows .NET projects.

Now, I’m not saying you HAVE to use ModernHttpClient. Far from it – Azure Mobile Apps is perfectly fine as-is and you won’t have any problems. If you want to use ModernHttpClient, then go for it – it “just works” – almost.

ModernHttpClient is a drop-in replacement for System.Net.Http.HttpClient. You add the NuGet package and away you go. It “just works”. If you really want to go all-in, then the suggestion is to replace the HttpClient constructor with this:

var httpClient = new HttpClient(new NativeMessageHandler());

Here is where the “almost” comes in. Azure Mobile Apps constructs the httpClient with a set of handlers that it creates. You can add things to the list of handlers in the MobileServiceClient constructor, but you can’t affect the actual constructor of the HttpClient that the MobileServiceClient uses.

Fortunately, this is easy to integrate. Normally, you would create a MobileServiceClient like this:

Multiple Message Handlers?

If you have read all the documentation and my blog series, you will note that this is acting as just another message handler. You can actually specify multiple message handlers, but – and this is important – the NativeMessageHandler() MUST be the last one listed. For instance, let’s say you’ve defined a Delegating Handler to do some logging. You would need to do the following:

Consider the request as going through layers of an onion, with the request actually being done by the inner-most layer. The order of the layers is listed in the array with the outer-most layer listed first.