Web API Controller


We created Web API with MVC project in the previous section where it generated a simple controller. Here, you will learn about Web API Controller in detail.
Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller.
Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.Web.Http.ApiController class. All the public methods of the controller are called action methods.
The following is a simple controller class added by visual studio by default when we created a new Web API project in the Create Web API Project section.
Example: Simple Web API Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPI.Controllers
{
    public class ValuesController : ApiController
    {
        // GET: api/student
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/student/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/student
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/student/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/student/5
        public void Delete(int id)
        {
        }
    }
}
As you can see in the above example, ValuesController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.
Based on the incoming request URL and HTTP verb (GET/POST/PUT/PATCH/DELETE), Web API decides which Web API controller and action method to execute e.g. Get() method will handle HTTP GET request, Post() method will handle HTTP POST request, Put() mehtod will handle HTTP PUT request and Delete() method will handle HTTP DELETE request for the above Web API.
The following figure illustrates the significance of Web API controller and action methods.
Web API Controller Overview
If you want to write methods that do not start with an HTTP verb then you can apply the appropriate http verb attribute on the method such as HttpGet, HttpPost, HttpPut etc. same as MVC controller.
Example: Simple Web API Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPI.Controllers
{
    public class ValuesController : ApiController
    {
        [HttpGet]
        public IEnumerable<string> Values()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpGet]
        public string Value(int id)
        {
            return "value";
        }

        [HttpPost]
        public void SaveNewValue([FromBody]string value)
        {
        }

        [HttpPut]
        public void UpdateValue(int id, [FromBody]string value)
        {
        }

        [HttpDelete]
        public void RemoveValue(int id)
        {
        }
    }
}

Web API Controller Characteristics

  1. It must be derived from System.Web.Http.ApiController class.
  2. It can be created under any folder in the project's root folder. However, it is recommended to create controller classes in the Controllers folder as per the convention.
  3. Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method.
  4. Return type of an action method can be any primitive or complex type. Learn more about it here.

Action Method Naming Conventions

As mentioned above, name of the action methods in the Web API controller plays an important role. Action method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as shown in the Web API Controller example above. However, you can append any suffix with HTTP verbs for more readability. For example, Get method can be GetAllNames(), GetStudents() or any other name which starts with Get.
The following table lists possible action method names for each HTTP method:
HTTP MethodPossible Web API Action Method NameUsage
GETGet() 
get()
GET()
GetAllStudent()
*any name starting with Get *
Retrieves data.
POSTPost()
post()
POST()
PostNewStudent()
*any name starting with Post*
Inserts new record.
PUTPut()
put()
PUT()
PutStudent()
*any name starting with Put*
Updates existing record.
PATCHPatch()
patch()
PATCH()
PatchStudent()
*any name starting with Patch*
Updates record partially.
DELETEDelete()
delete()
DELETE()
DeleteStudent()
*any name starting with Delete*
Deletes record.
The following figure illustrates the overall request/response pipeline.
Web API Request Pipeline
Visit Web API HTTP Message Life Cycle Poster for more details.

Difference between Web API and MVC controller

Web API ControllerMVC Controller
Derives from System.Web.Http.ApiController classDerives from System.Web.Mvc.Controller class.
Method name must start with Http verbs otherwise apply http verbs attribute.Must apply appropriate Http verbs attribute.
Specialized in returning data.Specialized in rendering view.
Return data automatically formatted based on Accept-Type header attribute. Default to json or xml.Returns ActionResult or any derived type.
Requires .NET 4.0 or aboveRequires .NET 3.5 or above

No comments:

Post a Comment