Create Image Server using WCF WEB HTTP Service

Last post I wrote on WCF Web HTTP Service: why and how. This post was for beginners in which I discussed how to get it started and write your fist WCF WEB HTTP Service. In this post we will go one step further and learn to work with streams or to be precisely images. Service will return image based on the input from client. We are going to create an image server. Image server will do following task

  • Read requested image from file system on server
  • Convert that to stream
  • Return stream to clients

We are going to create WCF WEB HTTP Service which will act as image server. So to start with let us create Service Contract.

 


using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Demo1
{    
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        Stream FetchImage(string imageName);      
       
    }
}


In above Service, there is one Operation Contract which returns a stream. Operation Contract can be accessed using baseurl/FetchImage?imageName={imagename with extension}. Client will pass image name in query parameter to fetch a particular image. If image is not present on image then null would be returned from service.

Service implementation is very simple. You need to do following steps to fetch image and return it as stream.

Step 1: First check for existence of the image. If it exists got to step 2 else go to step 4

Step 2: Read image as FileStream

Step 3: Set Outgoing Request Content Type as image/jpeg

Step 4: convert string Image does not exist as stream and return

Service is implemented as below,


public class Service1 : IService1
    {       

        public Stream FetchImage(string imageName)
        {
            string filePath = @"c:\\" + imageName;

            if (File.Exists(filePath))
            {
                FileStream fs = File.OpenRead(filePath);
                WebOperationContext.Current.OutgoingRequest.ContentType = "image/jpeg";
                return fs;
            }
            else
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(" Requested Image does not exist :(");
                MemoryStream strm = new MemoryStream(byteArray);
                return strm;
            }
        }        
    }


Service implementation is very simple but one line of code in which we are explicitly saying that outgoing response content type is image/jpeg

image

Already we have covered this in previous post about EndPoint configuration but for quick reference open markup of .svc file and add use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

image

This is what all you need to do to create an Image Server as WCF WEB HTTP Service. You can test server from IE browser.

image

And if requested image is not present then error message will be rendered as below,

image

Now you can go ahead and consume and work with this image server in any kind of client able to perform HTTP GET operation. In further post we will get into details of consuming this service from various kind of clients. I hope this post will help you.

WCF Web HTTP Service: why and how

Very often I talk on WCF to user groups and find developers confused on various forms of WCF. For example some of the questions I get are as follows

  • How to create REST Service
  • Can we create REST and SOAP Service together
  • What is WCF Web HTTP Service
  • How Web HTTP Service and WCF REST Service are different to each other
  • Can I host HTTP Service and REST Service in a console application
  • Why we need REST and HTTP Services
  • What kind of security can be applied on REST and HTTP Services and many more questions of this kind

In this post I will answer few of the above questions regarding WCF Web HTTP Services.

By definition, WCF Web HTTP programming model allows services to be exposed on non-SOAP EndPoints and helps to create WEB HTTP Services. Now a question may arise that why we need HTTP Services and what are the advantages of using that.

Mainly HTTP Services are designed and created for wide range of clients. Any application capable of following can be potential clients

  • Understand HTTP protocols and verbs
  • Can process URI and URL Schemes
  • Can work with different types of message and data formats
  • Perform HTTP Get and HTTP Post operations

Web HTTP Services doesn’t work on SOAP message format however any serilizable type can be returned from Web HTTP Services. Since HTTP Service does not work with SOAP so all WCF Security features cannot be applied on this. However basic Transport level security can be applied to WCF Web HTTP Services.

Let us see how we can create a very basic WCF Web HTTP Service. Create WCF Service Application project from WCF tab to create Web HTTP Service

image

After creation of project we need to create Service Contract.


 [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebGet]
        string HelloGet(string   name);

        [OperationContract]
        [WebInvoke]
        string  HelloPost(string  name);
       
    }


Above I have created very basic service. Service contains only two methods. One method will work on HTTP GET and other will work on HTTP POST operation. There are restrictions on passing parameters in query string. For example string can be passed in query parameter.


public class Service1 : IService1
    {       

        public string HelloGet(string name)
        {
            return "Hello GET " + name; 
        }

        public string HelloPost(string name)
        {
            return "Hello POST" + name; 
        }
    }



Above Service Contract is implemented as below. It’s very simple implementation in which service is returning string with concatenating of input string parameters.

Now there are various ways WCF WEB HTTP Services can be hosted and its EndPoint can be configured. You can configure and host service

  • In IIS
  • In Windows Services Application
  • In Managed Application like Console Application
  • Windows Azure Services

In this post let us learn how EndPoint can be configured for Web Server hosting like IIS. It’s very simple to configure EndPoints for HTTP Services. You can use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

image

You can fetch service from browser by navigating to URL as below. Keep in mind that port number could be different in your scenario.

http://localhost:55400/Service1.svc/HelloGet?name=dj

You can notice that we are passing input dj as string in query parameter. Response from service will be as below,

image

Another way service can be configured and hosted in a console application. In Console Application first you need to add reference of System.ServiceModel and System.ServiceModel.Web in the project.


using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using Demo1;

namespace ConsoleAppHostingService
{
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service1), new Uri("http://localhost:8989/"));
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1), new WebHttpBinding(), "");
            ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            sdb.HttpHelpPageEnabled = false;
            host.Open();
            Console.WriteLine("Service is running");
            Console.WriteLine("Press enter to quit...");
            Console.ReadLine();
            host.Close();

        }
    }
}


Few points about above hosting code are as follows

  • WEB HTTP Service should be hosted in a WebServiceHost instance.
  • WebHttpBinding is used to created HTTP Service
  • Help page is disabled

On running Console Application, service can be accessed on URL passed in WebServiceHost instance

image

In this way you can create WCF WEB HTTP Service. In further posts we will learn how to consume this service in various kind of clients and work with different kind of data format. I hope this post will help you.

CRUD operation on ASP.NET Web API from .NET client

In this post we will learn to work with CRUD operation on ASP.NET Web API. We will learn

  • To create CRUD operation on ASP.NET Web API
  • Using Entity model to create model
  • Creating repository to perform CRUD operation
  • Consuming service in .NET Console Client

I can draw architecture of this blog post as following,

image

Let us follow step by step approach to perform CRUD operation using ASP.NET Web API service.

Create ASP.Net Web API

In this part of blog, we will learn to create ASP.NET Web API. To create launch Visual Studio and create a project by choosing ASP.NET MVC 4 Web Application template.

image

Next you select Web API from the existing project template. Make sure to select Razor as View engine in drop down.

clip_image002

Next we need to add model. We will use ADO.Net Entity model to create model out of database. To add model, right click on the Models folder and select Add New Item. Next from Data tab select ADO.NET Entity Data Model

clip_image004

Next select Generate from database option and click on Next.

clip_image005

In next dialog box, you need to configure Connection Properties. Here select Northwind database after giving server name.

clip_image006

After configuring connection, you will get Entity Data Model Wizard populated with connection string as below. Click on next to proceed further

clip_image007

Here you need to select tables, views etc. For purpose of this post, let us select three tables, Customers, Employees and Products. After selecting tables click on Finish to create model of database in project.

clip_image008

We are going to work with Product table. To perform CRUD operation on this, let us go ahead and created a Repository. To create this right click on model and add an Interface from Code tab. I am giving name as IProductRepository.

clip_image010

In this interface we will define all the operations needed to be performed on Product table. Interface is defined as below,


using System.Collections.Generic;

namespace NorthwindService.Models
{
    public  interface IProductRepository
    {
        IEnumerable<Product> GetProducts();
        bool AddProduct(Product p);
        bool UpdateProduct(Product p);
        bool DeleteProduct(int ProductID);
    }
}

Next we need to implement CRUD operation. To do that add a class and implement IProductRepository in that class. Let us implement all four operations one by one.

Note : All these operations would be defined under ProductRepository class.

We can fetch all the Products as below by writing simple LINQ

public IEnumerable<Product> GetProducts()
        {
            NorthwindEntities entities = new NorthwindEntities();
            var products = from r in entities.Products select r;
            return products.ToList();
        }


A product can be added as below,


 public bool AddProduct(Product p)
        {
            try
            {
                NorthwindEntities entities = new NorthwindEntities();
                entities.Products.Add(p);
                entities.SaveChanges();
                return true; 
            }
            catch (Exception ex)
            {
                return false; 
            }

        }


Product can be updated as below,


public bool UpdateProduct(Product p)
        {
            try
            {
                NorthwindEntities entities = new NorthwindEntities();
                Product proudctToUpdate = (from r in entities.Products where 
                                               r.ProductID == p.ProductID select r).FirstOrDefault();

                proudctToUpdate.ProductName = p.ProductName;
                proudctToUpdate.UnitPrice = p.UnitPrice;
                entities.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


Product can be deleted as below,


public bool DeleteProduct(int productID)
        {
            try
            {
                NorthwindEntities entities = new NorthwindEntities();
                Product proudctToDelete = (from r in entities.Products
                                           where
                                               r.ProductID == productID
                                           select r).FirstOrDefault();
                entities.Products.Remove(proudctToDelete);
                entities.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

After creating repository for CRUD operation, let us go ahead and create Controller. To create Controller, right click on the Controller folder and select Add new Controller. You need to rename Controller name to ProductsController.

image

You will get controller class created as following. Make sure that you have changed Controller to ApiController

clip_image002[6]

Now we can create CRUD operation as below,

Products can be fetched as below,

static readonly IProductRepository repository = new ProductRepository();

        public IEnumerable<Product> GetProducts()
        {
            return repository.GetProducts();
        }

A new record can be created as following. We are passing Product as a resource to create here. While creating new record make sure

  • Action name is PostProduct. Essentially Action name should be started with Post to perform insert operation
  • Pass Product as input parameter
  • Return HttpResponse

We are calling AddProduct method of Repository class. Repository class is returning true on successful insertion of record. We are checking returned value and constructing returned HttpResponse.


public HttpResponseMessage PostProduct(Product p)
        {
            bool result = repository.AddProduct(p);
            HttpResponseMessage response;
            if(result)
            {
            response  = Request.CreateResponse(System.Net.HttpStatusCode.Created);
            }
            else
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            
            }
            return response ; 
        }

Modification of resource or Put operation can be performed as below. It is exactly same as Put operation with two differences

  • Action or function name starts from Put
  • UpdateProduct function of Repository class is being called.
  public HttpResponseMessage PutProduct(Product p)
        {
            bool result = repository.UpdateProduct(p);
            HttpResponseMessage response;
           if(result)
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
            }
            else
            {
                 response  = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            
            }
            return response ; 

        }

Delete of resource or Put operation can be performed as below. It is exactly same as other operation with two differences

  • Action or function name starts from Delete
  • It takes Id as input parameter to delete record with particular id
  • DeleteProduct function of Repository class is being called.

 public HttpResponseMessage DeleteProduct(int id)
        {
            bool result = repository.DeleteProduct(id);
            HttpResponseMessage response;
            if(result)
            {
            response  = Request.CreateResponse(System.Net.HttpStatusCode.OK);
            }
            else
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            
            }
            return response ; 

        }

This is what all you need to do to create ASP.NET Web API with CRUD operation on Northwind database.

Creating .NET or Console Client

We are going to create .NET Console client to consumer service we created earlier. To create Console Application project, you need to select Console Application project template from Windows tab. After creating project, right click on project and select manage Nuget packages. Here search for Microsoft.AspNet.WebApi.Client library. Install this NuGet package in client project.

image

After installing package, add following namespaces in project,


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

Before we perform any operation, first initialize following in the project. Below

  • Initializing HttpClient
  • Setting base address
  • Setting Http Request Header as JSON
 HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:37780/api/");
          
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));



After initializing HttpClient and base address, we need to create client side representation of Product class. Let us create Product class at client side. Make sure that definition of class is same as the server side. Client side Product class is as following,


public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public Nullable<int> SupplierID { get; set; }
        public Nullable<int> CategoryID { get; set; }
        public string QuantityPerUnit { get; set; }
        public Nullable<decimal> UnitPrice { get; set; }
        public Nullable<short> UnitsInStock { get; set; }
        public Nullable<short> UnitsOnOrder { get; set; }
        public Nullable<short> ReorderLevel { get; set; }
        public bool Discontinued { get; set; }
    }



Read Products from service

You can fetch all the Products as below.



 HttpResponseMessage response = client.GetAsync("products").Result;
            if (response.IsSuccessStatusCode)
            {
                var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
                foreach (var p in products)
                {
                    Console.WriteLine("{0}\t{1};\t{2}", p.ProductName, p.UnitPrice, p.QuantityPerUnit);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }


We are fetching records performing following steps in above code.

  • Records being fetched using GetAsync method of HttpClient class.
  • We are passing name of entity in GetAsync
  • After fetching records reading JSON data using Conent.ReadAsAsync() method of HttpResponseMessage
  • If response is erroneous then we are displaying error code as output.

Creating a Record

To create record or insert a record (in this case Product), we need to perform following steps ,

  • Create instance of product to be inserted
  • Perform PostAsJsonAsync operation on HttpClient and pass entity name and object to be inserted as parameter
  • On successful insertion you will get successful status code else error code.

Following code snippet will create a Product in database perform Put operation using ASP.NET Web API.


 Product p = new Product
            {
                ProductName = "DJ'S Pen",
                QuantityPerUnit = "20",
                Discontinued = true

            };
            HttpResponseMessage response = client.PostAsJsonAsync("products", p).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }


On successful creation of record you will get response as below,

clip_image001

Updating Record

Updating record is exactly same as creating record. Only you need to use PutAsJsonAsync() method. You can update a record as below,

Product p = new Product
            {
                ProductID = 90,
                ProductName = "DJ'S Bat",
                QuantityPerUnit = "20",
                Discontinued = true

            };
            HttpResponseMessage response = client.PutAsJsonAsync("products", p).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

On successful update you should get success message as below,

clip_image001[6]

Deleting Record

You can delete a resource using DeleteAsync function. You need to pass URI of the resource to be deleted.


HttpResponseMessage response = client.DeleteAsync("Products/90").Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

Here 90 is ProductId we want to delete. On successful deletion you will get success message as below,

clip_image001[8]

Conclusion

In this blog post we learn following items,

  1. Using ADO.NET Entity Model as model in Web API
  2. Creating CRUD operation on ASP.NET Web API
  3. Consuming service in .NET client

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

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.

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.

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

In this post I will give you basic understating of creating HTTP Services using ASP.NET Web API. Here I am assuming that you are aware of basic ASP.NET MVC.

To work with ASP.NET Web API, you need to install ASP.NET MVC 4.0. Download ASP.NET Web API from here and install it from Web Installer.

After installation create a new project choosing ASP.NET MVC 4 Web Application as project type.

image

Next choose Web API as template.

image

On examining project structure you will find it is exactly as usual ASP.NET MVC project structure. Let us go ahead and add a MODEL. For that right click on the Model folder and add a class. Let us add a model called Blogger

Blogger.cs


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

namespace firstwebapiapplication.Models
{
public class Blogger
{
public int Id { get; set; }
public string Name { get; set; }
public string Intrest { get; set; }
}
}

After adding Model let us go ahead and add Controller. There are two differences between Controller of usual ASP.NET MVC Controller and ASP.NET Web API Controller.

  • ASP.NET Web API Controller returns data not view
  • ASP.NET Web API Controller is derived from ApiController class.

Now go ahead and add a Controller called BloggerController. For that right click on Controller folder and add a controller.

image

Choose Empty Controller as Scaffolding options.

image

Next you need to change the class controller is inheriting. Change Controller to ApiController.

image

Controller class needs to inherit ApiController class from System.Web.Http namespace. Let us add a function to return information about Bloggers.

BloggerController.cs


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

namespace firstwebapiapplication.Controllers
{
public class BloggersController : ApiController
{
//
// GET: /Bloggers/



public IEnumerable<Blogger> GetAllBloggers()
{
return new List<Blogger>
{
new Blogger(){ Id= 1,Name="DebugMode",Intrest="ASP.NET Web API"},
new Blogger(){ Id= 2,Name="KodefuGuru",Intrest ="C Sharp"},
new Blogger(){ Id= 3,Name="ActiveNick",Intrest = "Windows Phone" },
new Blogger(){ Id= 4,Name= "GBLOCK ", Intrest ="REST"},
new Blogger(){ Id= 5,Name = "WadeWegner",Intrest = "Windows Azure " }
};
}

}
}


By this point you have created HTTP Service. Press F5 to host the service on Cassini server.

clip_image001

And you will get a file to download

clip_image003

Next we can consume it in any client. In later post I will show you to consume in JavaScript client and Windows Phone as well. I hope this introductory blog post is useful to get started with ASP.NET Web API. In next post we will get into consuming ASP.NET WEB API Services in various clients