Você está na página 1de 11

3/18/2014 Creating Simple Service with ASP.

NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 1/11
Article ID: 2778398
About Author:
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
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.
Creating Simple Service with ASP.NET MVC Web
API to be accessed by Windows Store and
Windows Phone Application
ASP.NET Web API
Create Blank Solution
This article is provided by M Reza Faisal (http://mvp.microsoft.com/en-us/mvp/Reza%20Faisal-4020676) . Microsoft is so thankful that MVPs who
proactively share their professional experience with other users. The article would be posted on MVP's website (http://mvp.microsoft.com/en-
us/mvp/Reza%20Faisal-4020676) or blog (http://geeks.netindonesia.net/blogs/reyza/) later.
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 2/11
The following image is a result that can be seen in the Solution Explorer.
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.
Create ASP.NET MVC Web API Project
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 3/11
The results can be seen in the Solution Explorer as shown below.
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.
Adding a Controller
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 4/11
In HelloWorldController.cs file will be added two methods as shown in the following example.
To call a Web API that has been made, we can do these following steps.
Writing HelloWorldController Codes
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
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 5/11
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/
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 6/11
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 :
Then the result can be seen in the picture below.
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.
http://localhost:33011/api/HelloWorld/M Reza Faisal
Create Windows Store Project
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 7/11
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.
Next we will work on MainPage.xaml. In MainPage.xaml will be added Button and TextBlock like in the picture below.
Calling Web API from Windows Store Application
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 8/11
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 Buttons action.
Here is the code in MainPage.xaml
And here is the code in MainPage.xaml.cs.
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
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; } } }
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 9/11
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.
Create Windows Phone Project
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 10/11
we can see the results as shown below.
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.
Calling the Web API from Windows Phone
3/18/2014 Creating Simple Service with ASP.NET MVC Web API to be accessed by Windows Store and Windows Phone Application
http://support.microsoft.com/kb/2778398 11/11
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.
Article ID: 2778398 - Last Review: April 1, 2013 - Revision: 2.0
Keywords: KB2778398
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?
Properties

Você também pode gostar