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.
At this point build the solution. Fireup Fiddler and issue a Post request
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.
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.
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.
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
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
- 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 you want to add to the database in JSON format
- Finally click execute
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.
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"
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.
ReplyDeleteGood morning
DeleteYou can get the last id by executing an sql query before inserting like this : select max(id) from "NameOfYourTable" ;
Hi
ReplyDeleteMany 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?
Hi
ReplyDeleteI am confused by the SQl reissue that you do... can you expand?
For Get request when an item is not found we have to return 404 Not Found.Typo error is there
ReplyDeleteusing above post code i'm getting wrong url
ReplyDeleteLocation: http://localhost:61438/api/Employee10
using VS2013.
What is Fiddler? Is that a software or a tool in Visual Studio?
ReplyDeleteThat 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.
DeleteYou can also try Postman, Restlet Client, etc available as extensions in google chrome.
Download fiddler from here https://www.telerik.com/download/fiddler
DeletePlease see part 3 of this Web API series.
Deletehttp://csharp-video-tutorials.blogspot.com/2016/09/aspnet-web-api-tutorial-for-beginners.html
You can use Postman or SoapUI as per your convenience
Delete{"FirstName":"Priti","LastName":"Shri","Gender":"Female","Salary":50000}
ReplyDeleteI entered getting error
HTTP/1.1 415 Unsupported Media Type
DeletedataType: "json",
Content-Type: application/json;odata=verbose;charset=utf-8