Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Implementing PUT method in ASP.NET Web API

Suggested Videos
Part 6 - ASP.NET Web API MediaTypeFormatter
Part 7 - Implementing post method in ASP.NET Web API
Part 8 - Implementing Delete method in ASP.NET Web API



In this video we will discuss implementing PUT method in ASP.NET Web API. PUT allows us to update an item.



Understanding Put method implementation is very easy if you have understood Post and Delete methods that we have discussed in Parts 7 and 8.

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. The Employee parameter is decorated with [FromBody] attribute. This tells Web API to get employee data from the request body.

public void Put(int id, [FromBody]Employee employee)
{
    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        var entity = entities.Employees.FirstOrDefault(e => e.ID == id);

        entity.FirstName = employee.FirstName;
        entity.LastName = employee.LastName;
        entity.Gender = employee.Gender;
        entity.Salary = employee.Salary;

        entities.SaveChanges();
    }
}

At this point build the solution. Fireup Fiddler and issue a Put request.
1. Set the HTTP verb to PUT
2. Content-Type: application/json. This tells that we are sending JSON formatted data to the server
3. In the Request Body, include the employee object with which you want to update 
4. Finally click execute

This works fine and updates the employee record in the database as expected. The problem here is that since the return type of the Put() method is void, we get status code of 204 No Content. When the update is successful, we want to return status code 200 OK indicating that the update is successful. Also when we try to update an employee whose Id does not exist we get back http status code 500 Internal Server Error. We get status code 500, because of a NULL reference exception. To fix both of these issues modify the code in Put() method as shown below.

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);
    }
}

At this point, issue another Put request from fiddler. Notice in the response header we have status code 200 OK. Also, when we try to update an employee whose id does not exist, we get status code 404 Not Found instead of 500 Internal Server Error

ASP.NET Web API tutorial for beginners

3 comments:

  1. instead of

    entity.FirstName = employee.FirstName;
    entity.LastName = employee.LastName;
    entity.Gender = employee.Gender;
    entity.Salary = employee.Salary;

    you can also write :

    entity = employee;
    entity.ID = id;
    entities.Employees.AddOrUpdate(entity);

    which is more easier to replicate if you have a lot of classes

    ReplyDelete
  2. As a parameter i'm passing "Eid", which is not working why ?

    ReplyDelete
    Replies
    1. You must pass parameter Id as WebAPI is expecting that if you pass Eid then web api will not expect something coming from the URL.

      Delete

It would be great if you can help share these free resources