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 world wide 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 server. It is important that use the corect method for the specifeid 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 use 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  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 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:


public static void RegisterRoutes(RouteCollection routes)

{

       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

       routes.MapHttpRoute(

              Name: "default_Api",

              route_Temp: "api/{controller}/{t_id}",

              defaults: new { id = RouteParameter.Optional }

       );

 

       routes.MapRoute(

              Name: "default_app",

              url: "{controller}/{action}/{t_id}",

              defaults: new { controller = "home", action = "Index", t_id =

                           UrlParameter.Optional }

       );

}

 

Now we create a service that remove the data and corresponingly modifies the other data, as in the following:

public static void RegisterRoutes(RouteCollection routes)

{

       routes.MapHttpRoute(

              Name: "Default_app",

              routeTemplate: "{controller}/{t_id}",

              defaults: new { t_id = RouteParameter.Optional }

       );

}

 

Now we create a resource task1, as in the following:

public class task1

{

       public int t_Id { get; set; }
       public string t_desciption { get; set;
      
public int t_prty { get; set; }

        public date_time Created { get; set; }

}

 

 We create the controller that exposes various methods that perform the resource, as in the following:

 

public class Task_Control : ApiController

{

           public IEnum<string> Get()

       {

          return new string[] { "val1", "val" };

       }
      
public string Get(int t_id)

       {

          return "val";

       }
      
public void Post(string val)

       {

       }
      
public void Put(int t_id, string val)

      

}

 

In this code we can see that the class Task_Control is derived from ApiController. It has the 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.

public class Task_Control : ApiController

{

       public IEnum<Task> Get()

       {

              throw new NotImplementedException();

       }
public Task Get(int t_id)

       {

              throw new NotImplementedException();

       }
      
public HttpResponseMessage<Task> Post(Task t_task)

       {

              throw new NotImplementedException();

       }
                 public Task Put(Task task)

       {

              throw new NotImplementedException();

       }

 

When we implement the task, first we need to store our task.

      

public interface ITask_Repos

{

       IEnume<Task> Get();

          Task Get(int t_id);

        Task Post(Task Task);

        Task Put(Task Task);

 }

 

  public class Task_Repos : ITask_Repos

{
 
private List<Task> Tasks

       {
          
get
             {
                   
if (HttpContext.Current.Cache["Task"] == null)

                           HttpContext.Current.Cache["Task"] = new List1<Task>();

                      return HttpContext.Current.Cache["Task"] as List1<Task>;             }

              set

              {

                   HttpContext.Current.Cache["Task"] = value;

              }

       }

        public IEnum<Task> Get()

       {

              return Task;

       }

      public Task Get(int t_id)

       {

              return Tasks.Find(p => p.t_Id == t_id);

       }
       
public Task Post(Task task)

       {
              t_task.t_Id = Tasks.Max(t => p.t_Id) + 1;

              Tasks.Add(task);

 
             
return t_task;

       }

 

       public Task Put(Task t_task)

       {

              var p = Get(t_task.t_id);

               if (p == null)

                     throw new Exception(string.Format("The Task is not exists.", task.t_Id));

               p.Description = t_task.Description;

              p.Priority = t_task.Priority;

              return p;

       }


 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.

 

private readonly ITask_Repos _task_Repos;

  public Tasks_Contrl(ITask_Repos task_Repos)

{

       _task_Repos = task_Repos;

}

 

GET() Method

This method returns all the tasks.

public IEnum<Task> Get()

{

       return _task_Repos.Get();

}


GET(T_id) Method

This method is used for the single variable.

public Task Get(int t_id)

{

       var t_task = _task_Repos.Get(t_id);

        if (t_task == null)

       {

              throw new HttpResponseException(new HttpResponseMessage

              {

                     StatusCode = HttpStatusCode.NotFound,

                     Content = new StringContent("This task is not available")

              });

       }

 

      return t_task;

}

 

Post(Task Task) Method

This method adds a resource.

public HttpResponseMessage<Task> Post(Task task)

{

       t_task = _task_Repos.Post(t_task);

 

       var t_Response = new HttpResponseMessage<Task>(task, HttpStatusCode.Created);

 

       string Uri = Url.Route(null, new { id = t_task.t_Id });

       response.Headers.Location = new Uri(Request.RequestUri, Uri);

 

       return t_Response;

}

 

Up Next
    Ebook Download
    View all
    Learn
    View all