REST Service in ASP.NET Web API

Introduction

 
Representational State Transfer (REST) is a service based on REST architecture. We can easily create REST services that can be used from other devices. The principles apply more on the web and HTTP. We can also use its principles in other distributed systems. In the worldwide web, there is an implementation of the REST architecture. We can easily implement the architecture on the other services. A simple service created using the REST architecture is called a REST service.
 
When we create the REST services it is important that we follow the rules of the HTTP protocol. Various APIs of various languages create and use the REST services. If we do not know the principle of REST then we can create the service but the service will work in the RPC style of service. So in this article we are will learn how to create a REST service.
 

REST

 
The REST architecture is based on the client and server. The client and server communicate with each other. It is based on the resource and request of the client and server and REST uses a uniform interface. In it, the client accesses the server's resource and the server returns the resource according to the client based request. The resource can be accessed by the address called a URI Address.
 
Architecture of REST
 
m5.jpg
 

What is Uniform Interface

 
Uniform Interface is an important feature of REST. It has a group of methods; they are GET, PUT, POST, DELETE, etc. These methods are easily understandable by the client and the server. It is important that use the correct method for the specified action. If the request is based on the GET method and it chooses the DELETE method then the resource will be DELETEd. That would be a problem for the other methods that do perform the appropriate action.
 

What is ASP.NET Web API

 
The ASP.Net Web API has a controller that is called the API controller. For developing MVC there are using two types of controllers.
 
The first one is the API controller and the second one is the default MVC controller. It is important to choose the correct controller for the specified action. On the creation of the REST service, we use the API controller. These controllers return the data. And we use the default controller for returning the views.
 
Sample for creating the simple service
 
We provide a sample for creating a simple service that manages all the tasks. Before creating it we need to identify the resources of the application and select the right method and address related to resources.
 
here we provide an example of a mapping table-
 
Action Method URI
Get all the Task GET /tasks
Get a single method GET /tasks/id
Create a new task POST /tasks
Edit a task PUT /task/id
Delete a task DELETE /task/id
 
Now we create a new ASP.Net MVC4 web application
 
m2.jpg

We select the empty template for the creation of the MVC4 application.
 
m3.jpg
 
In the Global.asax.cs. there are two routes defined; the first is MVC controller and the second is API controller, as in the following:
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.    
  5.        routes.MapHttpRoute(  
  6.               Name: "default_Api",  
  7.               route_Temp: "api/{controller}/{t_id}",  
  8.               defaults: new { id = RouteParameter.Optional }  
  9.        );  
  10.    
  11.        routes.MapRoute(  
  12.               Name: "default_app",  
  13.               url: "{controller}/{action}/{t_id}",  
  14.               defaults: new { controller = "home", action = "Index", t_id =  
  15.                            UrlParameter.Optional }  
  16.        );  
Now we create a service that removes the data and correspondingly modifies the other data, as in the following:
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.        routes.MapHttpRoute(  
  4.               Name: "Default_app",  
  5.               routeTemplate: "{controller}/{t_id}",  
  6.               defaults: new { t_id = RouteParameter.Optional }  
  7.        );  
Now we create a resource task1, as in the following:
  1. public class task1  
  2. {  
  3.        public int t_Id { getset; }  
  4.        public string t_desciption { getset;  
  5.        public int t_prty { getset; }  
  6.         public date_time Created { getset; }  
We create the controller that exposes various methods that perform the resource, as in the following:
  1. public class Task_Control : ApiController  
  2. {  
  3.            public IEnum<string> Get()  
  4.        {  
  5.           return new string[] { "val1""val" };  
  6.        }  
  7.        public string Get(int t_id)  
  8.        {  
  9.           return "val";  
  10.        }  
  11.        public void Post(string val)  
  12.        {  
  13.        }  
  14.        public void Put(int t_id, string val)  
  15.         
In this code, we can see that the class Task_Control is derived from ApiController. It has the method for Get all the tasks, Get a single task, create a new task, and edit the task.
 
now we describe the return type of method.
  1. public class Task_Control: ApiController {  
  2.     public IEnum < Task > Get() {  
  3.       throw new NotImplementedException();  
  4.     }  
  5.     public Task Get(int t_id) {  
  6.       throw new NotImplementedException();  
  7.     }  
  8.     public HttpResponseMessage < Task > Post(Task t_task) {  
  9.       throw new NotImplementedException();  
  10.     }  
  11.     public Task Put(Task task) {  
  12.       throw new NotImplementedException();  
  13.     } 
When we implement the task, first we need to store our task.
  1. public interface ITask_Repos {  
  2.   IEnume < Task > Get();  
  3.   Task Get(int t_id);  
  4.   Task Post(Task Task);  
  5.   Task Put(Task Task);  
  6. }  
  7.   
  8. public class Task_Repos: ITask_Repos {  
  9.     private List < Task > Tasks {  
  10.       get {  
  11.         if (HttpContext.Current.Cache["Task"] == null)  
  12.           HttpContext.Current.Cache["Task"] = new List1 < Task > ();  
  13.         return HttpContext.Current.Cache["Task"as List1 < Task > ;  
  14.       }  
  15.       set {  
  16.         HttpContext.Current.Cache["Task"] = value;  
  17.       }  
  18.     }  
  19.     public IEnum < Task > Get() {  
  20.       return Task;  
  21.     }  
  22.     public Task Get(int t_id) {  
  23.       return Tasks.Find(p => p.t_Id == t_id);  
  24.     }  
  25.     public Task Post(Task task) {  
  26.       t_task.t_Id = Tasks.Max(t => p.t_Id) + 1;  
  27.       Tasks.Add(task);  
  28.   
  29.       return t_task;  
  30.     }  
  31.   
  32.     public Task Put(Task t_task) {  
  33.       var p = Get(t_task.t_id);  
  34.       if (p == null)  
  35.         throw new Exception(string.Format("The Task is not exists.", task.t_Id));  
  36.       p.Description = t_task.Description;  
  37.       p.Priority = t_task.Priority;  
  38.       return p;  
  39.     } 
In this code, Task_Repos is a class that is derived from the ITask_Repos interface. In it, we use the HttpContext.Current.Cache that stores the task.
  1. private readonly ITask_Repos _task_Repos;  
  2. public Tasks_Contrl(ITask_Repos task_Repos)  
  3. {  
  4.        _task_Repos = task_Repos;  
GET() Method
 
This method returns all the tasks.
  1. public IEnum<Task> Get()  
  2. {  
  3.        return _task_Repos.Get();  
GET(T_id) Method
 
This method is used for a single variable.
  1. public Task Get(int t_id)  
  2. {  
  3.        var t_task = _task_Repos.Get(t_id);  
  4.         if (t_task == null)  
  5.        {  
  6.               throw new HttpResponseException(new HttpResponseMessage  
  7.               {  
  8.                      StatusCode = HttpStatusCode.NotFound,  
  9.                      Content = new StringContent("This task is not available")  
  10.               });  
  11.        }  
  12.    
  13.       return t_task;  
Post(Task Task) Method
 
This method adds a resource.
  1. public HttpResponseMessage<Task> Post(Task task)  
  2. {  
  3.        t_task = _task_Repos.Post(t_task);  
  4.    
  5.        var t_Response = new HttpResponseMessage<Task>(task, HttpStatusCode.Created);  
  6.    
  7.        string Uri = Url.Route(nullnew { id = t_task.t_Id });  
  8.        response.Headers.Location = new Uri(Request.RequestUri, Uri);  
  9.    
  10.        return t_Response;