ASP.Net Web API Service in Windows Phone: Part 4 of Many

Creating First HTTP Service using ASP.NET Web API: Part1 of Many

Consuming ASP.NET Web API Service using HttpClient: Part2 of Many

How to Self-Host ASP.Net Web API: Part 3 of Many

In this post we will consume ASP.Net Web API HTTP Service in Windows Phone Application. If you do not specify header information in HTTP request then by default ASP.Net Web API service returns JSON data. So essentially there are three steps involved in consuming HTTP Service from ASP.Net Web API in Windows Phone Application.

  1. Make a HTTP Request
  2. Read data from HTTP Response
  3. Parse returned JSON data and bind data to data bound control

In this post we are going to consume service created in this POST

I have created a Windows Phone Application by choosing target framework 7.1. We are going to display Bloggers Data returned from ASP.Net Web API service in a ListView. Essentially we are going to consume a JSON Data from a HTTP Service. For that add below references in the project.

image

We are going to de-serialize JSON data using DataContractJsonSerializer class. We need to create a class at client side representing Bloggers entity from the service. Let us create a class called BloggersClient. We will de-serialize JSON data returning from the HTTP service in this object of this class.


namespace WindowsPhoneClient
{
public class BloggersClient
{
public string Id { get; set; }
public string Name { get; set; }
public string AreaOfIntrest { get; set; }

}
}

Once the client class is in placed add following references,

image

We are going to download JSON data from ASP.Net Web API service using WebClient class. Make sure that you are passing URL of your HTTP Service.

image

In the completed event, we will parse returned JSON using DataContractJsonSerializer class. In following code,

  • Creating MemoryStream form returned result
  • Creating object to de-serialize the returned JSON data
  • Reading de-serialized data object in List of BloggersClient
  • Setting List of BloggerClient as ItemSource of ListBox. On the XAML we have put a ListBox with name lstBloggers.

image

Code behind to load data from ASP.Net Web API HTTP Service on page load of the application and s display in ListBox is as following


using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace WindowsPhoneClient
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:39192/api/Bloggers"));
}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream s = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<BloggersClient>));
List<BloggersClient> result = (List<BloggersClient>) ser.ReadObject(s);
lstBloggers.ItemsSource = result;
}
}
}

On the XAML, we have put ListBox control do bind data from HTTP Service in the control.

If you are not aware of Data Binding in ListBox then watch a quick Video here


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="ASP.Net Web API" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="lstBloggers">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
<TextBlock Text="{Binding AreaOfIntrest}" Style="{StaticResource PhoneTextAccentStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>

Now press F5 to run the application. You should able to get Bloggers detail from ASP.Net Web API service in Windows Phone Application.

image

I hope you find this post useful. Thanks for reading.

About these ads

How to Self-Host ASP.Net Web API: Part 3 of Many

Creating First HTTP Service using ASP.NET Web API: Part1 of Many
Consuming ASP.NET Web API Service using HttpClient: Part2 of Many

In this post, we will step by step walkthrough that How to Self-Host ASP.Net Web API. We are going to host Web API in a console application. To do that creates a Console Application.

image

After creating Console Application make sure to change target framework to .NET Framework 4.0. To change framework right click on the project and select Properties and choose .NET Framework 4 from drop down

image

Next we need to add reference of ASP.Net Web API. We will add reference using NuGet. We will add NuGet Web API package. To add this right click on the project and click on Manage NuGet Package

image

In the search box type Microsoft.AspNet.WebApi.SelfHost and click on search button. Make sure to install Microsoft ASP.NET Web API Self Host in the project.

image

Accept the license term to install the package.

image

By this time we have set up the environment for self-hosting of Web API. Next we will add a Model class. To add that right click and add a class to the project.

Bloggers.cs


namespace webapihostapp
{
public class Bloggers
{
public string Id { get; set; }
public string Name { get; set; }
public string AreaOfIntrest { get; set; }
}
}

Next we will add a Controller class. To add that right click and add a class to the project. Make sure that you are appending Controller with the class name. For example you want to give controller name as abc then make sure that you are giving class name ABController. In this case we are giving controller name BloggersController .

image

Controller class needs to be inherited from ApiController class.

image

Next we need to write Action in the controller. We are writing a simple Action and this is returning List of Bloggers. Controller class will look like following

BloggersController.cs


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

namespace webapihostapp
{
public class BloggersController :ApiController
{
public List<Bloggers> GetBloggers()
{
return new List<Bloggers>
{
new Bloggers { Id="1", AreaOfIntrest ="Sql Server " , Name ="Pinal Dave"},
new Bloggers { Id="2", AreaOfIntrest ="ASP.Net " , Name =" Suprotim Agarwal " },
new Bloggers { Id="3", AreaOfIntrest ="C Sharp " , Name ="ShivPrasad Koirala"},
new Bloggers { Id="4", AreaOfIntrest ="Sql Server" , Name =" vinod Kumar " },
new Bloggers { Id="5", AreaOfIntrest ="JavaScript " , Name ="John Papa"},
new Bloggers { Id="6", AreaOfIntrest ="Dan Wahlin " , Name ="HTML5" },
new Bloggers { Id="7", AreaOfIntrest ="Business Intelligence " , Name ="Stephen Forte"},
new Bloggers { Id="8", AreaOfIntrest ="Web API " , Name ="Glen Block" },
new Bloggers { Id="9", AreaOfIntrest ="Windows Azure " , Name ="Gaurav Mantri"},
new Bloggers { Id="10", AreaOfIntrest ="Entity Framework" , Name ="Julie Lerman " },
new Bloggers { Id="11", AreaOfIntrest ="HTML" , Name ="John Bristow"},
new Bloggers { Id="12", AreaOfIntrest ="Silverlight" , Name ="Kunal" },

};

}
}
}

As of now we have Model and Controller in place. We will write code in Program file to host the Web API. Very first add the following namespaces in Program.cs

image

Then create instance of HttpSelfHostConfiguration

image

Next add a default route

image

After adding default route we need to create instance of HttpSelfHostServer and pass the configuration we just created as parameter.

image

Consolidating all the discussion together code to self-host ASP.Net Web API would be as following

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace webapihostapp
{
class Program
{
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://localhost:9999");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}");

using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
}
}

Now press F5 to run the application

image

Now browse to URL and should able to download Bloggers detail as JSON.

image

In this way we can self-host ASP.Net Web API in a console application. I hope you find this post useful. Thanks for reading.

Consuming ASP.NET Web API Service using HttpClient: Part2 of Many

Read Part 1 Here

I am in love with ASP.NET Web API hence I started writing on the same. In first part of this blog series I have written Creating First HTTP Service using ASP.NET Web API: Part1 of Many.

In this post I will show you how you could consume service created in previous blog post in a managed application?

Service is hosted at http://localhost:14892/api/Bloggers

To download JSON data from service as string you can use WebClient class from System.Net as below. In below code essentially we are downloading JSON data as string from the service.


using System;
using System.Net;

namespace ConsoleApplication39
{
class Program
{
static void Main(string[] args)
{
using(WebClient proxy = new WebClient())
{
var response = proxy.DownloadString("http://localhost:14892/api/Bloggers");
Console.WriteLine(response);
Console.ReadKey(true);

}
}
}
}

As output you will get downloaded string on console

clip_image001

In above code while making call to service; we are not providing any header type and as response we are getting JSON since default serealizer of ASP.NET Web API is JSON serealizer. If you want to get XML data as response then you need to set Accept Header type to XML. Below code will download XML data from the service.


using System;
using System.Net;

namespace ConsoleApplication39
{
class Program
{
static void Main(string[] args)
{
using(WebClient proxy = new WebClient())
{
proxy.Headers.Add(HttpRequestHeader.Accept, "application/xml");
var response = proxy.DownloadString("http://localhost:14892/api/Bloggers");
Console.WriteLine(response);
Console.ReadKey(true);

}
}
}
}

On Console you will get expected XML as below,

clip_image002

Other than WebClient class, you can use HttpClient class. It is rich Http Client for .NET. It exposed the API to

  1. Receive HttpResponseMessage
  2. Send HttpRequestMessage

To work with HttpClient class you need to add below DLL in the project. You can download these dll from here

clip_image001[7]

You can download data as JSON array using HttpClient as below. We are downloading data asynchronously and using properties name printing them.


using System;
using System.Net.Http;
using System.Json;

namespace ConsoleApplication39
{
class Program
{
static void Main(string[] args)
{

HttpClient proxy = new HttpClient();
proxy.GetAsync("http://localhost:14892/api/Bloggers").ContinueWith((r) =>
{
HttpResponseMessage response = r.Result;
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(a)=>
{
foreach(var w in a.Result)
{
Console.WriteLine(w.ValueOrDefault("Name").ToString());
Console.WriteLine(w.ValueOrDefault("Intrest").ToString());
}
});

});

Console.ReadKey(true);

}

}
}

You will be getting output on console as below.

clip_image001[9]

Now question may come to your mind that why to use HttpClient over WebClient? You can use same instance of HttpClient to make as many call to service as you want. HttpClient allows you to configure headers extension etc.

In this way you can consume an Http Service created using ASP.Net Web API in a managed client. I hope this post is useful. Thanks for reading.