ASP.Net Simple Web API

Here, I would like to describe how to create a HTTP service using the Web API in ASP.NET and I will explain how to create a client consume the Web API.

In this tutorial I will explain how to do Create, Update, Retrieve and Delete (CRUD) operations in a HTTP service.

In this tutorial I will explain a very simple Web Application Programing Interface (API) to manage employee records. Each employee contains an Employee ID (UID), Name, Address and City.

SNO. Action HTTP Method Relative URI
1 Get List of Employees GET /api/Employee
2 Get Employee by ID GET /api/Employee?uid=uid
3 Get Employee by City GET /api/Employee?City=City
4 Create New Employee Post /api/Employee
5 Update Existing Employee Put /api/Employee/uid
6 Delete Employee record Delete /api/Employee/uid

This article explains the first three points.

Create HTTP service using ASP.NET Web API

Step 1: Start VS2012 then select "File" -> "New" -> "Project...".


Step 2: Web -> ASP.NET MVC 4 Web Application then click OK.

MVC 4 Web Application

Step 3: Web API then click OK.


Step 4: Adding MODEL

A model is an object that represents the data in your application. In the ASP.NET Web API, you can use strongly typed CLR objects as models and they will automatically be serialized to XML or JSON for the client.

Here I have created a class named Employee.

In Solution Explorer, right-click the Models folder. From the context menu, select Add, then select Class. Name the class "Employee".

Adding MODEL

Adding the following properties to the Employee class.
  1. namespace DEMOHttpServiceWebAPI.Models    
  2. {    
  3.     public class Employee    
  4.     {    
  5.         Public int Uid { getset; }    
  6.         public string Name { getset; }    
  7.         public string Address { getset; }    
  8.         public string City { getset; }    
  9.     }    
  10. } 

Step 5: Adding Controller

In the ASP.NET Web API, a controller is a class that handles HTTP requests from the client. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in the Solution Explorer.

  • HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site and is not directly related to our web API.
  • ValuesController is an example WebAPI controller.

Proceed to and delete ValuesController by right-clicking the file in Solution Explorer and selecting Delete. Now add a new controller, as follows.

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.


In the Add Controller window, name the controller EmployeeController. In the template dropdown list, select Empty API controller. Then Click oK.

Empty API controller

Add this namespace to the controller class
  1. using DEMOHttpServiceWebAPI.Models;  
Getting Resource

Here EmployeeController exposes the read action as a HTTP GET method.
Action HTTP Method Relative URI
Get List of Employee GET /api/Employee
Get Employee by ID GET /api/Employee?id=id
Get Employee by City GET /api/Employee?City=City

Note: All method names should begin with Get.

To get a list of all employees add this method to the EmployeeController class:

This method return list of all employee. URI for this method is: "/api/Employee?City=City"

  1. /// This method return list of all employee  
  2. /// </summary>  
  3. /// <returns></returns>  
  4. public List<Employee> GetAllEmployee()  
  5. {  
  6.     return _emp;  

To get an employee by ID add this method to the EmployeeController class.

This method returns an employee of a given uid. If the uid is not available in the list then it throws an exception with status code NotFound. The URI for this method is: /api/Employee?id=id”.

  1. /// <summary>  
  2. /// This method return Employee detail of given id  
  3. /// </summary>  
  4. /// <param name="uid"></param>  
  5. /// <returns></returns>  
  6. public Employee GetEmployee([FromUri]int uid)  
  7. {  
  8.     Employee emp = GetAllEmployee().Find(p => p.Uid == uid);  
  9.     if (emp == null)  
  10.    {  
  11.        throw new HttpResponseException(HttpStatusCode.NotFound);  
  12.    }  
  13.     return emp;  

To get an employee by city add this method to the EmployeeController class.

This method returns a list of employees of a given city. The URI for this method is: “/api/Employee?City=City”.

  1. /// <summary>  
  2. /// This method Return list of employee by City.  
  3. /// </summary>  
  4. /// <param name="city"></param>  
  5. /// <returns></returns>  
  6. public List<Employee> GetEmployeeByCity([FromUri] string city)  
  7. {  
  8.     return GetAllEmployee().Where(p => string.Equals(p.City, city, StringComparison.OrdinalIgnoreCase)).ToList();  

Step 6: Now In this step I will explain how to consume a HTTP service Web API in .Net.

Create a console application in VS2012 then select "File" -> "New" -> "Project...".

In the templates pane expand Visual C# and select Console Application and write the application name and click OK.

console application

Install the Web API Client Libraries

From the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebAPI.Client

Adding Class in Console application

Add the following class to the console application:
  1. public class Employee  
  2. {  
  3.     public int Uid { getset; }  
  4.     public string Name { getset; }  
  5.     public string Address { getset; }  
  6.     public string City { getset; }  

Note: This class matches the data model used in the "Employee" Web API project.

Then add this method in the Program.cs file.

  1. private static HttpResponseMessage ClientRequest(string RequestURI)  
  2. {  
  3.     HttpClient client = new HttpClient();  
  4.     client.BaseAddress = new Uri("http://localhost:1379/");  
  5.     client.DefaultRequestHeaders.Accept.Clear();  
  6.     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  7.     HttpResponseMessage response = client.GetAsync(RequestURI).Result;  
  8.     return response;  

This code creates a Httpclient class object and sets the base address (URI of the HTTP Request) and sets the accept header to "application/json" that tells the server to send the data in JSON format.

GetAsync: This method sends the HTTP request. When the method is complete it returns the httpresponsemessage that contains the HTTP Response.

If the status code in the response is the success code then the response body contains the JSON format Employee data. Then call the ReadAsAsyn method to deserialized the JSON fromat data in the Employee class instance.

For exception handling use the EnsureSuccessStatusCode method. This method throws an exception when the status code is not the success code.

  1. try    
  2. {      
  3.     response.EnsureSuccessStatusCode(); //throw if success code is not success      
  4. }      
  5. catch (HttpRequestException ex)      
  6. {      
  7.     throw ex;      
  8. } 

Add following code to the Main function of Program->Get All Employee List.

  1. HttpResponseMessage responseAllEmployee = ClientRequest("api/Employee");  
  2. responseAllEmployee.EnsureSuccessStatusCode();  
  3. if (responseAllEmployee.IsSuccessStatusCode)  
  4. {  
  5.     Console.WriteLine("---------------Get All Employee list------------");  
  6.     List<Employee> _user = responseAllEmployee.Content.ReadAsAsync<List<Employee>>().Result;  
  7.     foreach (Employee _Empdata in _user)  
  8.     {  
  9.         Console.WriteLine("{0}\t{1}\t{2}\t{3}", _Empdata.Uid, _Empdata.Name, _Empdata.Address, _Empdata.City);  
  10.     }  

Add this code to the Main function of the Program->Get Employee by UID.

  1. Console.WriteLine("----------------Get Employee By ID-------------------");  
  2. Console.WriteLine("Enter Employee ID=>");  
  3. string empid = Console.ReadLine();  
  4. HttpResponseMessage response = ClientRequest("api/Employee?uid=" + empid);  
  5. response.EnsureSuccessStatusCode();  
  6. if (response.IsSuccessStatusCode)  
  7. {  
  8.     Employee _Empdata = response.Content.ReadAsAsync<Employee>().Result;  
  9.     Console.WriteLine("{0}\t{1}\t{2}\t{3}", _Empdata.Uid, _Empdata.Name, _Empdata.Address, _Empdata.City);  

Add this code to the Main function of Program->Get Employee by City.

  1. Console.WriteLine("----------------Get Employee By City-------------------");  
  2. Console.WriteLine("Enter City=>");  
  3. string City = Console.ReadLine();  
  4. HttpResponseMessage responseEmployeeByCity = ClientRequest("api/Employee?city=" +City);  
  5. responseEmployeeByCity.EnsureSuccessStatusCode();  
  6. if (responseEmployeeByCity.IsSuccessStatusCode)  
  7. {  
  8.     List<Employee> _Empdata = responseEmployeeByCity.Content.ReadAsAsync<List<Employee>>().Result;  
  9.     foreach (Employee _Empdata1 in _Empdata)  
  10.     {  
  11.         Console.WriteLine("{0}\t{1}\t{2}\t{3}", _Empdata1.Uid, _Empdata1.Name, _Empdata1.Address, _Empdata1.City);  
  12.     }  

Then you will run your application and see the following output.


For a full demo of this application download the attachment.

In the next article, I will explain how to insert a new record using the INSERT-POST Method of HTTP.

Similar Articles