• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Monday, April 20, 2020

How to Implement PUT Method in Web API

 Admin     April 20, 2020     .Net, Web API     No comments   

In this article, I am going to discuss how to Implement PUT Method in Web API with one example. Please read our previous article where we discussed how to implement the POST Method in Web API before proceeding to this article as we are going to work with the same example.

How to Implement PUT method in ASP.NET Web API?
The PUT method in Web API allows us to update an item. Here, we want to update the 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 the [FromBody] attribute. This tells Web API to get employee data from the request body.
public class EmployeesController : ApiController
{
    public void Put(int id, [FromBody]Employee employee)
    {
        using (EmployeeDBContext dbContext = new EmployeeDBContext())
        {
            var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
            entity.FirstName = employee.FirstName;
            entity.LastName = employee.LastName;
            entity.Gender = employee.Gender;
            entity.Salary = employee.Salary;
            dbContext.SaveChanges();
        }
    }
}

At this point build the solution, run the application and fire up Fiddler and issue a Put request.
  • Set the HTTP verb to PUT
  • Content-Type: application/json. This tells that we are sending JSON formatted data to the server
  • In the Request Body, include the updated employee object with which you want to update
  • Finally, click on the execute button as shown below
Implementing PUT Method in WEB API

When we click on the Execute button, it will give us the below response.
Implementing PUT Method in WEB API

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 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 the Put method as shown below.
public class EmployeesController : ApiController
{
    public HttpResponseMessage Put(int id, [FromBody]Employee employee)
    {
        try
        {
            using (EmployeeDBContext dbContext = new EmployeeDBContext())
            {
                var entity = dbContext.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;
                    dbContext.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

Summary:
I Hope this post will be helpful to understand How to implement PUT Method in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • Anonymous Types in C#
    Hi friends! Today we are going to learn about Anonymous Types in C#. Let's start with the Introduction Anonymous is a type that does...
  • Web API Attribute Routing Route Constraints
    In this article, I will discuss the Web API Attribute Routing Route Constraints with examples. We are going to work with the same example ...
  • Entity Types in Entity Framework
    In this article, I am going to discuss the Entity Types in Entity Framework in detail. Please read our previous article where we discussed...
  • What is Web API in Asp.Net
    In this article, I will be introducing you to ASP.NET WEB API Framework. At the end of this article, you will be having a very good underst...
  • Usability of SecureString object in C#
    Introduction Hi friends! In this blog we will be discussing a very interesting as well as useful topic in C# and that is Securestring objec...
  • Reverse Number Program in C# with Examples
    In this article, I am going to discuss the Reverse Number Program in C# with some examples. Please read our previous article where we discu...
  • Connecting to SQL Server using SSMS
    Introduction Hi friends! In this blog we will be discussing How to connect to the SQL Server using SQL Server Management Studio (SSMS). ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape