• 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 POST Method in Web API

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

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

How to Implement the POST Method in Web API Application?
The Post Method in Web API application allows us to create a new item. Here, we want to add a new Employee to the Employees table. First, Include the following Post() method within the EmployeesController. Notice that the Employee object is being passed as a parameter to the Post method. The Employee parameter is decorated with the [FromBody] attribute. We will discuss [FromBody] attribute in details in a later article but for now to understand this [FormBody] attribute tells the Web API to get the employee data from the request body.
public class EmployeesController : ApiController
{
    public void Post([FromBody] Employee employee)
    {
        using (EmployeeDBContext dbContext = new EmployeeDBContext())
        {
            dbContext.Employees.Add(employee);
            dbContext.SaveChanges();
        }
    }
}

At this point build the solution. Run the application and Fire up Fiddler and issue a Post request
  • Set the HTTP verb to POST
  • Content-Type: application/json. This tells that we are sending JSON formatted data to the server
  • In the Request Body, include the employee object that we want to add to the Employees database table in JSON format
  • Finally, click on the Execute button as shown in the below image
Implementing POST Method in WEB API

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

This works fine and adds the employee to the database as expected. The problem here is that since the return type of the Post method is void, we get status code 204 No Content. As per REST standard, when a new item is created, it should return the status code 201 Item Created. With 201 status code, we may also include the location i.e. URI of the newly created item.

Let’s see how to achieve this. To achieve this, we need to modify the POST method as shown below.
public class EmployeesController : ApiController
{
    public HttpResponseMessage Post([FromBody] Employee employee)
    {
        try
        {
            using (EmployeeDBContext dbContext = new EmployeeDBContext())
            {
                dbContext.Employees.Add(employee);
                dbContext.SaveChanges();
                var message = Request.CreateResponse(HttpStatusCode.Created, employee);
                message.Headers.Location = new Uri(Request.RequestUri +
                    employee.ID.ToString());
                return message;
            }
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }
}

At this point, issue another Post request from Fiddler. Notice in the response header we have status code 201 Created and also the location i.e. the URI of the newly created item as shown in the below image.
Implementing POST Method in WEB API

Points to Remember while working with Web API Post Method:
  • If a method return type is void in Web API Service then by default Web API Service return the status code 204 No Content.
  • 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.
  • When an item is not found, instead of returning NULL and status code 200 OK, return 404 Not Found status code along with a meaningful message such as “Employee with Id = 15 not found“
Summary:
I Hope this post will be helpful to understand how to implement POST 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

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...
  • ASP.NET Core Attribute Routing using Tokens
    In this article, I am going to discuss the ASP.NET Core Attribute Routing using Tokens with examples. Please read our previous article bef...

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