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.
- using System;
- using System.Collections.Generic;
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Net.Http.Formatting;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- namespace ContocoClient
- {
- publicclassRecipeDataAgent
- {
- publicasyncTask<IEnumerable<RecipeDataItemDto>> GetRecipeDataItemsAsync()
- {
- var client = new HttpClient();
- client.BaseAddress = newUri(“http://contosorecipes8.blob.core.windows.net/”);
- var jsonTypeFormatter = new JsonMediaTypeFormatter();
- jsonTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“application/octet-stream”));
- var response = await client.GetAsync((“AzureRecipesRP”));
- returnawait response.Content.ReadAsAsync<List<RecipeDataItemDto>>(new[] { jsonTypeFormatter }); ;
- }
- }
- publicclassRecipeDataItemDto
- {
- [JsonProperty(“key”)]
- publicstring UniqueId
- { get; set; }
- publicstring Title
- { get; set; }
- }
- }
2. In Visual Studio, go to ContosoClient and add the following code to Program.cs.
using ContocoClient;
- namespace ContosoConsole
- {
- classProgram
- {
- staticvoid Main(string[] args)
- {
- CallRecipeServiceAsync().Wait();
- }
- publicstaticasync Task CallRecipeServiceAsync()
- {
- var recipes = awaitnew RecipeDataAgent().GetRecipeDataItemsAsync();
- foreach (var receipe in recipes)
- {
- Console.WriteLine(receipe.Title);
- }
- }
- }
- }
4. In Visual Studio, go to ContosoStore and add the following code into the <Page> element in MainPage.xaml.
- <GridBackground=“{StaticResource ApplicationPageBackgroundThemeBrush}“>
- <ListViewx:Name=“itemListView“/>
- </Grid>
5. In MainPage.xaml.cs, add the following method to the MainPage class.
- public async void UpdateListView()
- {
- var recipes = await new RecipeDataAgent().GetRecipeDataItemsAsync();
- foreach (var receipe in recipes)
- {
- itemListView.Items.Add(receipe.Title);
- }
- }
6. Call the UpdateListView method from the NavigatedTo method.
- protectedoverridevoid OnNavigatedTo(NavigationEventArgs e)
- {
- UpdateListView();
- }
7. Run the Windows Store app by pressing Ctrl+F5. The app will show the titles in the list view.[DR2]
Summary
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!
0 comments