Consuming Web API in Windows Store Apps

Software Requirement

  • Windows 8
  • Visual Studio 2012 RC
  • MVC 4.0

In my previous article, I had explained the steps for creating a Web API. So I assume that after reading my previous article, you are able to create a Web API.

Build and run this project on your local computer. The client will access the API at http://localhost:1234/api/Users.

Currently, Windows Metro style apps don't support Web API Client Libraries but you can still use HttpClient in Windows Metro style apps, without the media-formatter capabilities provided by the Web API Client Libraries.

Now I am going to create one Metro style app for consuming a Web API.

Steps for creating a Metro Style Project

Start Visual Studio 2012 RC and select New Project from the Start page. Or, from the File menu, select New and then Project.

Select Installed Templates and expand the Visual C# node. Under Visual C#, select Windows Metro Style. In the list of project templates, select Blank App (XAML). Name the project "FirstMetroStyleApp" and click OK.


Now open the MainPage.xaml and write this code:


    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Orientation="Vertical">

            <StackPanel Orientation="Horizontal">

                <Button x:Name="btnGetUsers" Click="GetUser" Content="Get Users"/>


 Grid.Column="1" Margin="15,0,0,0">
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                <TextBlock x:Name="OutputView" FontSize="16" Height="Auto" Margin="15,0,0,0" TextWrapping="Wrap" />

And now open MainPage.XAML.cs and write this code:

private HttpClient httpClient;
public MainPage()
            httpClient = new HttpClient();
            httpClient.BaseAddress =
new Uri("http://localhost:1234/");
new MediaTypeWithQualityHeaderValue("application/json"));
// Limit the max buffer size for the response so we don't get overwhelmed
            httpClient.MaxResponseContentBufferSize = 256000;
/// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
private async void GetUser(object sender, RoutedEventArgs e)
btnGetUsers.IsEnabled =
var response = await httpClient.GetAsync("api/users");
// Throw on error code.
var users = await response.Content.ReadAsStringAsync();
OutputView.Text = users;

In this I have taken one button; when the user clicks on this button, it fetches the user list and shows it on the screen. Now build the application and see the result.


By this way we can consume an ASP.Net Web API in a Windows Metro Style App.

That's All.

Up Next
    Ebook Download
    View all
    View all