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

Implementing post method in ASP.NET Web API

Suggested Videos
Part 3 - HTTP GET PUT POST DELETE
Part 4 - ASP.NET Web API and SQL Server
Part 5 - ASP.NET Web API Content Negotiation



In this video we will discuss implementing POST method in ASP.NET Web API. Post allows us to create a new item.



We want to add a new Employee to the Employees table. Include the following Post() method in EmployeesController. Notice the Employee object is being passed as parameter 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 Post([FromBody] Employee employee)
{
    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        entities.Employees.Add(employee);
        entities.SaveChanges();
    }
}

At this point build the solution. Fireup Fiddler and issue a Post request
  1. Set the HTTP verb to POST
  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 that you want to add to the database in JSON format
  4. Finally click execute
asp.net web api post json fiddler

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 of 204 No Content. When a new item is created, we should actually 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. To achieve this, change the implementation of the Post() method as shown below.

public HttpResponseMessage Post([FromBody] Employee employee)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            entities.Employees.Add(employee);
            entities.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.
asp net web api post complex type

Let's also modify Get(int id) method. At the moment when we issue a request for an employee id that does not exist, we get null back and the status code is 200 OK. According to the standards of REST when an item is not found we should be returning 204 Not Found. To achieve this modify the Get(int id) method as shown below.

public HttpResponseMessage Get(int id)
{
    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        var entity = entities.Employees.FirstOrDefault(e => e.ID == id);
        if (entity != null)
        {
            return Request.CreateResponse(HttpStatusCode.OK, entity);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                "Employee with Id " + id.ToString() + " not found");
        }
    }
}

At this point, when we issue a request for an employee with ID = 101 which does not exist we get a 404 along with the message "Employee with Id 101 not found"

Here are the important points to remember
  • If a method return type is void, by default status code 204 No Content is returned.
  • 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 = 101 not found"
ASP.NET Web API tutorial for beginners

13 comments:

  1. Thank you for this great tutorial. How can I get the last inserted Id if I am using a stored procedure for inserting. I added an output parameter to the stored proc but it always returns 0.

    ReplyDelete
    Replies
    1. Good morning
      You can get the last id by executing an sql query before inserting like this : select max(id) from "NameOfYourTable" ;

      Delete
  2. Hi
    Many thanks for these great tutorials. I did the same as you did but when I tried to use post method to insert new employee I got this error: "HTTP/1.1 405 Method Not Allowed"
    Could you tell my how I can fix it?

    ReplyDelete
  3. Hi
    I am confused by the SQl reissue that you do... can you expand?

    ReplyDelete
  4. For Get request when an item is not found we have to return 404 Not Found.Typo error is there

    ReplyDelete
  5. using above post code i'm getting wrong url
    Location: http://localhost:61438/api/Employee10
    using VS2013.

    ReplyDelete
  6. What is Fiddler? Is that a software or a tool in Visual Studio?

    ReplyDelete
    Replies
    1. That is a software, which acts as a client to your server(Visual Studio) so that you can Get as well as Post data to it along with other operations.
      You can also try Postman, Restlet Client, etc available as extensions in google chrome.

      Delete
    2. Download fiddler from here https://www.telerik.com/download/fiddler

      Delete
    3. Please see part 3 of this Web API series.
      http://csharp-video-tutorials.blogspot.com/2016/09/aspnet-web-api-tutorial-for-beginners.html

      Delete
    4. You can use Postman or SoapUI as per your convenience

      Delete
  7. {"FirstName":"Priti","LastName":"Shri","Gender":"Female","Salary":50000}

    I entered getting error
    HTTP/1.1 415 Unsupported Media Type

    ReplyDelete
    Replies

    1. dataType: "json",
      Content-Type: application/json;odata=verbose;charset=utf-8

      Delete

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