Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application


Author: M Reza Faisal

ASP.NET Web API

ASP.NET MVC 4 Web API is one of new feature that can be found in Visual Studio 2012.

ASP.NET Web API is a framework that allows to make HTTP service that can be consumed by a web application on a web browser, a desktop application or mobile application. Web APIs are very useful as a source of data for the native app like Windows Store or Windows Phone application. Format output of Web API can be XML, JSON or the other.

In this article will explain how to create a simple HTTP service to be consumed by Windows Store and Windows Phone application

↑ Back to the top


Create Blank Solution

Here are the steps to create an Blank Solution in Visual Studio 2012 :
  1. On menu select FILE > New > Project.
  2. In Template window, select Installed > Templates > Other Project Types > Visual Studio Solutions.
  3. Choose Blank Solution, and fill Name with HelloWorldSolution.
  4. Click OK button.



The following image is a result that can be seen in the Solution Explorer.




↑ Back to the top


Create ASP.NET MVC Web API Project

After Blank Solution is made, the next step is adding a Web API Project in the Solution.

We can add ASP.NET MVC 4 Web API project into Solution by doing these steps :
  1. Right click on Solution 'HelloWorldSolution' in the Solution Explorer
  2. Choose Add > New Project.
  3. In Installed Templates pane select Templates> Visual C #> Web> ASP.NET MVC 4 Web Application.
  4. Fill HelloWorldWebAPI in Name textbox.
  5. Click OK button.
  6. Select Web API on ASP.NET MVC 4 pane New Project template, and then click the OK button.




The results can be seen in the Solution Explorer as shown below.




↑ Back to the top


Adding a Controller

Next we will make a simple Controller class to handle HTTP request.

These are the steps to add a Controller :
  1. Right click on the Controller folder then select Add > Controller.
  2. In the Add Controller pane, enter a name HelloWorldController as name of Controller class.
  3. In the area Scaffolding options > Template select Empty API Controller.
  4. Then click the Add button.




↑ Back to the top


Writing HelloWorldController Codes

In HelloWorldController.cs file will be added two methods as shown in the following example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace HelloWorldWebAPI.Controllers
{
public class HelloWorldController : ApiController
{
// GET api/HelloWorld
public string Get()
{
return "Hello World";
}

// GET api/HelloWorld/id
public string Get(string id)
{
return "Hello " + id;
}
}
}

↑ Back to the top


Calling Web API from the Web Browser

To call a Web API that has been made, we can do these following steps.

On the menu select Debug > Start Debugging or we can press F5 key. The result can be seen as following picture.




We can see the results of HelloWorldController.cs by accessing this url http://localhost:33011/api/HelloWorld/



The response from the request is JSON formatted, and this is the content of the file. The response from the request will be different if we use the Firefox as web browser. In Firefox, the response from the request is XML formatted.



In the controller has two methods, to access the method Get (string id) can be done by accessing this url :
http://localhost:33011/api/HelloWorld/M Reza Faisal

Then the result can be seen in the picture below.




↑ Back to the top


Create Windows Store Project

In the above example has shown how to call a web API from a web browser. Now it will be shown how to create a Windows Store app to accessing Web APIs. The following are the steps to create a Windows Store Project :
  1. First step, add a project to the solution, right click on the Solution and select Add> New Project
  2. In the Add New Project pane, select Installed> Visual C #> Windows Store> Blank App (XAML)
  3. In the Name textbox, type HelloWorldWS as name of your project
  4. Then click the OK button


Now we can see HelloWorldWS project in Solution Explorer.




↑ Back to the top


Calling Web API from Windows Store Application

Next we will work on MainPage.xaml. In MainPage.xaml will be added Button and TextBlock like in the picture below.




Here is a function of two items :
  1. Button will have function to access the Web API.
  2. TextBlock will display the results of the Button’s action.

Here is the code in MainPage.xaml



And here is the code in MainPage.xaml.cs.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using System.Net.Http;
using System.Net.Http.Headers;

namespace HelloWorldWS
{
public sealed partial class MainPage : Page
{
private HttpClient hc;

public MainPage()
{
this.InitializeComponent();

hc = new HttpClient();
string uriStr = "http://localhost:33011/api/HelloWorld/";

if (!String.IsNullOrEmpty(TextBox_Name.Text))
{
uriStr = "http://localhost:33011/api/HelloWorld/" + TextBox_Name.Text;
}

hc.BaseAddress = new Uri(uriStr);
hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
}

private async void Button_AccessWebAPI_Click(object sender, RoutedEventArgs e)
{
var response = await hc.GetAsync("api/HelloWorld/");
response.EnsureSuccessStatusCode(); // Throw on error code.

var result = await response.Content.ReadAsStringAsync();

TextBlock_Result.Text = result;
}
}
}

The following are the steps to run the Windows Store app with Visual Studio 2012 :
  1. Right click on the Windows Store Project in the Solution Explorer
  2. Select Debug> Start New Instance


↑ Back to the top


Create Windows Phone Project

Next will make a simple Windows Phone 7.5 application to access Web API.

To make Windows Phone 7.5 application, we will use the Visual Studio 2010 Express for Windows Phone, because Windows Phone project template is not available yet in Visual Studio 2012 when this article was written.


These are the steps to create a Windows Phone app project :
  1. On the menu select File > New Project.
  2. In the Installed Templates pane, select Visual C # > Silverlight Windows Phone.
  3. Type HelloWorldWP as the project name.
  4. Click the OK button.
  5. Select the Windows Phone OS 7.1 on Windows Phone OS Target Version option.
  6. Click the OK button.




we can see the results as shown below.




↑ Back to the top


Calling the Web API from Windows Phone

Next we will work on MainPage.xaml. In MainPage.xaml will be added Button and TextBlock as shown below.




Here are the contents of the file MainPage.xaml and MainPage.xaml.cs.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace HelloWorldWP
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void Button_AccessWebAPI_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
string uriStr = "http://localhost:33011/api/HelloWorld/";


if (!String.IsNullOrEmpty(TextBox_Name.Text))
{
uriStr = "http://localhost:33011/api/HelloWorld/"+TextBox_Name.Text;
}

Uri uri = new Uri(uriStr);

wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_GetTrends_DownloadStringCompleted);
wc.DownloadStringAsync(uri);
}

void wc_GetTrends_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
TextBlock_Result.Text = e.Result;
}
catch (Exception ex)
{
TextBlock_Result.Text = ex.Message;
}
}
}
}

↑ Back to the top


What is Next?

This article has briefly introduce ASP.NET MVC 4 Web APIs, the next article will explain more about the Web API.

↑ Back to the top


Community solutions content disclaimer

Microsoft corporation and/or its respective suppliers make no representations about the suitability, reliability, or accuracy of the information and related graphics contained herein. All such information and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information and related graphics, including all implied warranties and conditions of merchantability, fitness for a particular purpose, workmanlike effort, title and non-infringement. You specifically agree that in no event shall Microsoft and/or its suppliers be liable for any direct, indirect, punitive, incidental, special, consequential damages or any damages whatsoever including, without limitation, damages for loss of use, data or profits, arising out of or in any way connected with the use of or inability to use the information and related graphics contained herein, whether based on contract, tort, negligence, strict liability or otherwise, even if Microsoft or any of its suppliers has been advised of the possibility of damages.

↑ Back to the top


Keywords: kb

↑ Back to the top

Article Info
Article ID : 2778398
Revision : 4
Created on : 7/18/2018
Published on : 12/19/2018
Exists online : False
Views : 105