Create Web API for CRUD operation - Part 4: Implement Put Method

This section is a continuation of the previous three sections where we created necessary infrastructure for the Web API and also implemented GET & POST methods. Here, we will implement PUT method in the Web API.

The HTTP PUT method is used to update an existing record in the data source in the RESTful architecture.

So let's create an action method in our StudentController to update an existing student record in the database using Entity Framework. The action method that will handle HTTP PUT request must start with a word Put. It can be named either Put or with any suffix e.g. PUT(), Put(), PutStudent(), PutStudents() are valid names for an action method that handles HTTP PUT request.

The following example demonstrates Put action method to handle HTTP PUT request.

Example: Put Method in Web API Controller

public class StudentController : ApiController
{

    public StudentController()
    {
    }

    public IHttpActionResult Put(StudentViewModel student)
    {
        if (!ModelState.IsValid)
            return BadRequest("Not a valid model");

        using (var ctx = new SchoolDBEntities())
        {
            var existingStudent = ctx.Students.Where(s => s.StudentID == student.Id)
                                                    .FirstOrDefault<Student>();

            if (existingStudent != null)
            {
                existingStudent.FirstName = student.FirstName;
                existingStudent.LastName = student.LastName;

                ctx.SaveChanges();
            }
            else
            {
                return NotFound();
            }
        }

        return Ok();
    }
}

As you can see above, Put action method includes a parameter of StudentViewModel. It then creates new student entity using passed StudentViewModel object and then changes the state to be modified.

Now, you can send HTTP PUT request using Fiddler as shown below and see the response.

Execute PUT request in Fiddler

As you can see in the above figure, HTTP PUT request includes StudentViewModel object into JSON format in the request body. After successfull execution the response status is 200 OK.

Next, implement Delete action method to handle HTTP DELETE request in the Web API.