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.
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 the following properties to the Employee class.
- namespaceDEMOHttpServiceWebAPI.Models
- {
- publicclassEmployee
- {
- Public int Uid { get; set; }
- publicstring Name { get; set; }
- publicstring Address { get; set; }
- publicstring City { get; set; }
- }
- }
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.
Add this namespace to the controller class
- usingDEMOHttpServiceWebAPI.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"
-
-
-
- public List<Employee> GetAllEmployee()
- {
- 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”.
-
-
-
-
-
- public Employee GetEmployee([FromUri]int uid)
- {
- Employee emp = GetAllEmployee().Find(p => p.Uid == uid);
- if (emp == null)
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- 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”.
-
-
-
-
-
- public List<Employee> GetEmployeeByCity([FromUri] string city)
- {
- 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.
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:
- public class Employee
- {
- public int Uid { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- }
Note: This class matches the data model used in the "Employee" Web API project.
Then add this method in the Program.cs file.
- private static HttpResponseMessage ClientRequest(string RequestURI)
- {
- HttpClient client = new HttpClient();
- client.BaseAddress = new Uri("http://localhost:1379/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.GetAsync(RequestURI).Result;
- 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.
- Try{
- response.EnsureSuccessStatusCode();
- }
- catch (HttpRequestException ex)
- {
- throw ex;
- }
Add following code to the Main function of Program->Get All Employee List.
- HttpResponseMessage responseAllEmployee = ClientRequest("api/Employee");
- responseAllEmployee.EnsureSuccessStatusCode();
- if (responseAllEmployee.IsSuccessStatusCode)
- {
- Console.WriteLine("---------------Get All Employee list------------");
- List<Employee> _user = responseAllEmployee.Content.ReadAsAsync<List<Employee>>().Result;
- foreach (Employee _Empdata in _user)
- {
- 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 the Program->Get Employee by UID.
- Console.WriteLine("----------------Get Employee By ID-------------------");
- Console.WriteLine("Enter Employee ID=>");
- string empid = Console.ReadLine();
- HttpResponseMessage response = ClientRequest("api/Employee?uid=" + empid);
- response.EnsureSuccessStatusCode();
- if (response.IsSuccessStatusCode)
- {
- Employee _Empdata = response.Content.ReadAsAsync<Employee>().Result;
- 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.
- Console.WriteLine("----------------Get Employee By City-------------------");
- Console.WriteLine("Enter City=>");
- string City = Console.ReadLine();
- HttpResponseMessage responseEmployeeByCity = ClientRequest("api/Employee?city=" +City);
- responseEmployeeByCity.EnsureSuccessStatusCode();
- if (responseEmployeeByCity.IsSuccessStatusCode)
- {
- List<Employee> _Empdata = responseEmployeeByCity.Content.ReadAsAsync<List<Employee>>().Result;
- foreach (Employee _Empdata1 in _Empdata)
- {
- Console.WriteLine("{0}\t{1}\t{2}\t{3}", _Empdata1.Uid, _Empdata1.Name, _Empdata1.Address, _Empdata1.City);
- }
- }
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.