You are currently offline, waiting for your internet to reconnect

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

About Author:

This article is provided by M Reza Faisal. Microsoft is so thankful that MVPs who proactively share their professional experience with other users. The article would be posted on MVP's website or blog later.
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
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.



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.


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.




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;        }    }}
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.



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.



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


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.



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;            }        }    }}
What is Next?
This article has briefly introduce ASP.NET MVC 4 Web APIs, the next article will explain more about the Web API.

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.
Properties

Article ID: 2778398 - Last Review: 04/01/2013 03:13:00 - Revision: 2.0

  • KB2778398
Feedback
ng = 1; var varCustomerTracking = 1; var Route = "76500"; var Ctrl = ""; document.write(" rack by $index -->
Venezuela - Español
microsoft.com/c.gif?DI=4050&did=1&t="> var varCustomerTracking = 1; var Route = "76500"; var Ctrl = ""; document.write(" ocument.getElementsByTagName('head')[0].appendChild(m);" onload="var m=document.createElement('meta');m.name='ms.dqp0';m.content='false';document.getElementsByTagName('head')[0].appendChild(m);" src="http://c1.microsoft.com/c.gif?">