Writing Web API Client Code for Multiple Platforms Using Portable Libraries


The Microsoft ASP.NET Web API Client Libraries make it easy to write .NET clients that interact with RESTful HTTP services. Unfortunately, until recently the Web API client libraries did not support all platforms. Because of this limitation, developers had to maintain different code, depending on the target platform.

The new release of Microsoft ASP.NET Web API Client Libraries now comes with support for building portable libraries that target .NET 4.5, Windows Store and Windows Phone 8 applications. This support is built on the recently released portable HttpClient and the portable library support in Json.NET. Developers can now build a single portable library that can be used to consume Web APIs from Windows Phone and Windows Store apps as well as from middle-tier logic running on .NET 4.5

This blog post shows you how to create a reusable portable class library that consumes a sample HTTP service, and then how to use the library from a client application that targets multiple platforms.

Create the projects for different platforms

1. We will create three projects; a portable class library, which will actually use the Web API Client Libraries, a console application and a Windows Store app, which are the clients that will consume the portable library.
Create a new project named ContosoClient in C# with the Portable Class Library template. This is the common library that the other projects will use. The template is located under the Windows tab of the New Project dialog box:


2. In the Add Portable Class Library dialog, select the .NET Framework 4.5, Windows Phone 8, and .NET for Windows Store apps target platforms. Depending on the target platforms that you select, different .NET profile will be used for this project.


Note: This release of Microsoft ASP.NET Web API Client Libraries does not support Xbox 360, Silverlight, or Windows Phone 7.5 and lower. I won’t show how to create a Windows Phone 8[MW1] project in this article, but the ContosoClient portable library also supports Windows Phone 8.

3. Create a Windows console app named ContosoConsole.

4. Create a Windows Store app named ContosoStore with the Blank App (XAML) template as follows:


Configure the projects for the Web API Client Libraries

1. In Visual Studio, right-click the ContosoClient solution, and then select Manage NuGet Packages for solution. In the Manage NuGet Packages dialog, select Online->All in the left pane, select Include Prelease, and then search for “Microsoft.AspNet.WebApi.Client” as follows:


2. Click the Install button to install the Web API Client Libraries in all three of the projects that we created.

Note: Instead of having a single assembly set working for all the supported platforms, the Web API Client Libraries have two different sets of assemblies, depending on the target platforms. Because of this, you should install the package in all of the clients, although they do not directly use the libraries.

3. In Visual Studio, add a reference to ContosoClient to both of ContosoConsole and ContosoStore as follows:


Update the projects to consume Contoso Recipe Service

1. In Visual Studio, go to ContosoClient, and then add the following code. It calls the Contoso Recipe sample service, and deserializes the JSON result into a list of RecipeDataItemDto objects. The recipe service returns much more data regarding each recipe, but in this sample we only serialize the title and ID, in order to simplify the code.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Net.Http;
  6. using System.Net.Http.Formatting;
  7. using System.Net.Http.Headers;
  8. using System.Threading.Tasks;
  9. using Newtonsoft.Json;
  11. namespace ContocoClient
  12. {
  13.     publicclassRecipeDataAgent
  14.     {
  16.         publicasyncTask<IEnumerable<RecipeDataItemDto>> GetRecipeDataItemsAsync()
  17.         {
  19.             var client = new HttpClient();
  21.             client.BaseAddress = newUri(“http://contosorecipes8.blob.core.windows.net/”);
  23.             var jsonTypeFormatter = new JsonMediaTypeFormatter();
  25.             jsonTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“application/octet-stream”));
  27.             var response = await client.GetAsync((“AzureRecipesRP”));
  29.             returnawait response.Content.ReadAsAsync<List<RecipeDataItemDto>>(new[] { jsonTypeFormatter }); ;
  31.         }
  33.     }
  34.     publicclassRecipeDataItemDto
  35.     {
  36.         [JsonProperty(“key”)]
  37.         publicstring UniqueId
  38.         { get; set; }
  40.         publicstring Title
  41.         { get; set; }
  42.     }
  43. }

2. In Visual Studio, go to ContosoClient and add the following code to Program.cs.

using ContocoClient;

Code Snippet
  1. namespace ContosoConsole
  2. {
  3.     classProgram
  4.     {
  5.         staticvoid Main(string[] args)
  6.         {
  7.             CallRecipeServiceAsync().Wait();
  8.         }
  10.         publicstaticasync Task CallRecipeServiceAsync()
  11.         {
  12.             var recipes = awaitnew RecipeDataAgent().GetRecipeDataItemsAsync();
  13.             foreach (var receipe in recipes)
  14.             {
  15.                 Console.WriteLine(receipe.Title);
  16.             }
  17.         }
  18.     }
  19. }

3. Run the console application by pressing Ctrl+F5. The application will show the title of the all the recipes that the service returns:


4. In Visual Studio, go to ContosoStore and add the following code into the <Page> element in MainPage.xaml.

Code Snippet
  1. <GridBackground=“{StaticResource ApplicationPageBackgroundThemeBrush}>
  2.   <ListViewx:Name=itemListView/>
  3. </Grid>

5. In MainPage.xaml.cs, add the following method to the MainPage class.

Code Snippet
  1. public async void UpdateListView()
  2. {
  3.     var recipes = await new RecipeDataAgent().GetRecipeDataItemsAsync();
  4.     foreach (var receipe in recipes)
  5.     {
  6.         itemListView.Items.Add(receipe.Title);
  7.     }
  8. }

6. Call the UpdateListView method from the NavigatedTo method.

Code Snippet
  1. protectedoverridevoid OnNavigatedTo(NavigationEventArgs e)
  2. {
  3.     UpdateListView();
  4. }

7. Run the Windows Store app by pressing Ctrl+F5. The app will show the titles in the list view.[DR2]



The Web API Client Libraries make it easy to write Web API clients, but until now you had to maintain different source code for each platform using platform-specific APIs. With this release you can now write portable Web API client code that targets .NET 4.5, Windows Store apps and Windows Phone 8 apps. Enjoy!


Discussion is closed.

Feedback usabilla icon