GET, POST, DELETE & PUT Method in ASP.NET Web API

This tutorial will have sample code to for Get, Post, Delete & Put method.

For demonstration purposes we are considering application with employee data as EF, we will perform different operation on it.

GET Method :- We want to get Employee data by ID, Fot this we included the following Get() method in EmployeesController.

public HttpResponseMessage Get(int id)
{
    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        var entity = entities.Employees.FirstOrDefault(e => e.ID == id);// Get Data
        if (entity != null)
        {
            return Request.CreateResponse(HttpStatusCode.OK, entity);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                "Employee with Id " + id.ToString() + " not found");
        }
    }
}


POST Method :- We want to add a new Employee to the Employees table. Fot this we included the following Post() method in EmployeesController. Notice the Employee object is being passed as parameter to the Post method. The Employee parameter is decorated with [FromBody] attribute. This tells Web API to get employee data from the request body.

public HttpResponseMessage Post([FromBodyEmployee employee)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            entities.Employees.Add(employee);
            entities.SaveChanges();

            var message = Request.CreateResponse(HttpStatusCode.Created, employee);
            message.Headers.Location = new Uri(Request.RequestUri +
                employee.ID.ToString());//For return url

            return message;
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}


DELETE Method :- We want to delete the specified employee from the Employees table. Include the following Delete() method in EmployeesController.


public HttpResponseMessage Delete(int id)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            //Check if emp exists
            var entity = entities.Employees.FirstOrDefault(e => e.ID == id);
            if (entity == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                    "Employee with Id = " + id.ToString() + " not found to delete");
            }
            else
            {
                entities.Employees.Remove(entity);
                entities.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}


PUT Method :- We want to update employee by Id. Include the following Put() method in EmployeesController. Notice the id of the employee that we want to update and the Employee object with which we want to update are being passed as parameters to the Post method.


public HttpResponseMessage Put(int id, [FromBody]Employee employee)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            var entity = entities.Employees.FirstOrDefault(e => e.ID == id);
            if (entity == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                    "Employee with Id " + id.ToString() + " not found to update");
            }
            else
            {
                entity.FirstName = employee.FirstName;
                entity.LastName = employee.LastName;
                entity.Gender = employee.Gender;
                entity.Salary = employee.Salary;

                entities.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK, entity);
            }
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}


You can observe that, I have changed return type from void to HttpResponseMessage, this is to have proper message on requrest completion. Alos added try catch block to handel errors.
  • If a method return type is void, by default status code 204 No Content is returned.
  • When a new item is created, we should be returning status code 201 Item Created.
  • With 201 status code we should also include the location i.e URI of the newly created item. 

How System know if method is for GET or POST?

  • By default, the HTTP verb GET is mapped to a method in a controller that has the name Get() or starts with the word Get
  • Even if you rename Get() method in above code to GetEmployees() or GetAllEmployee() it will still be mapped to the HTTP verb GET as long as the name of the method is prefixed with the word Get. 
  • The word Get is case-insensitive. It can be lowercase, uppercase or a mix of both.
  • If the method is not named Get or if it does not start with the word get then Web API does not know to which the GET request must be mapped and the request fails with an error message stating The requested resource does not support http method 'GET' with the status code 405 Method Not Allowed if methof is rename to LoadEmployees() 
  • To instruct Web API to map HTTP verb GET to LoadEmployees() method, decorate the method with [HttpGet] attribute.
  • Method overloading can be used to have multiple methods or to pass parameter.
  • Following attributes are used to map custom named methods in the controller class to GET, POST, PUT and DELETE http verbs.
  • Attribute

    Maps to http verb

    [HttpGet]

    GET

    [HttpPost]

    POST

    [HttpPut]

    PUT

    [HttpDelete]

    DELETE


Parameter Binding- FromBody and FromUri

We can change this default parameter binding process by using [FromBody] and [FromUri] attributes.In example below
  1. Decorated id parameter with [FromBody] attribute, this forces Web API to get it from the request body
  2. Decorated employee parameter with [FromUri] attribute, this forces Web API to get employee data from the URI (i.e Route data or Query String)
public HttpResponseMessage Put([FromBody]int id, [FromUri]Employee employee)
{
------
}


Comments