Update Resource using PUT Method in Asp.Net Web API

In “Create Resource Using POST Method in Rest Asp.Net Web API” article, we discussed how to create resources. Today we discuss how we can update the resource in Asp.Net Web API using the HTTP PUT method.

using CompanyRestAPI.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CompanyRestAPI.Controllers
{
    public class EmployeesController : ApiController
    {
        // PUT: Update Employee
        [Route("api/employees/updateemployee")]
        [HttpPut]
        public HttpResponseMessage UpdateEmployee([FromBody] Employee emp)
        {
            try
            {
                if (emp == null || !ModelState.IsValid)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }

                bool isSuccess = Company.UpdateEmployee(emp);
                return Request.CreateResponse(HttpStatusCode.OK, (isSuccess == true) ? "Success" : "Failure");
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }
}

As shown above, we have declared the HTTP Verb attribute as HttpPut for UpdateEmployuee method. Here we are passing total employee record as input and updating all fields in the particular employee record based on it’s Id. In the next article, we will discuss how to invoke the PUT method using the Fiddler tool.

                                                                                                CompanyRestAPI-PUT-05082020.zip (55.62 mb)

Add comment