Post Method In ASP.NET Web API

Introduction

Flip to Visual Studio.

First, comment the CustomFormatter class which we had used in our previous article ASP.NET Web API MediaTypeFormatter. So, we will comment that class. 



Now, in EmployeesController, we will add a POST Method. Here, POST method allows us to add a new employee in our employeeData Table.



At the moment in the employeesData Table, we have five rows. Now, let’s flip to Visual Studio and let’s implement a method for POST



As in the POST parameter, we have added employeesData and instance as employee;  now where is this employee going to come from? Now, when a client makes a request a request has a request header, URI and request body. The data here for the employee object is going to come from request body and we tell that web API by declaring this employeeData in parameter with an attribute. We will specify an attribute, from Body attribute,which basically means this attribute will be telling the data for that employee which we had specified in the parameter so our code with attribute is,
  1. public void post ([FromBody]employeesData employee)    
  2. {    
  3. }  
Now we will create an instance of TestEntities DB Entities
  1. public void post ([FromBody]employeesData employee)    
  2. {    
  3.     using (TESTEntities entities = new TESTEntities())    
  4.     {    
  5.         entities.employeesDatas.Add(employee);    
  6.         entities.SaveChanges();    
  7.     }  
  8. } 
Now, let's save our changes and reload the app. Now open fiddler and issue a POST request .



Kindly change the HTTP verb to POST and check the URL. Remember the POST method we had specified --  that request is going to come from request body by declaring it from Body attribute so within the request body in the fiddler we have to include the data for the employee object.



I had copied some dummy data in the request body as you can see from the above screenshot. So this is JSON formatted data so we need to tell Web API we will be sending JSON formatted data to tell that we include content-type header as,



Now, execute that request. When you will execute that request go to SQL and check whether data has been inserted or not.
 


As you can see from the above output the data has been inserted successfully. This works fine but when you inspect the records we had got,


We got 204 No content; that’s because the return type of the POST method is Void.  By default Web API is going to return Status Code 204 No content.

According to the standards of REST when we add a new item we should be actually returning status code 201 item created and along with status code 204. We should also be returning the location which is the URI of the newly created item. So let’s see how to achieve this,

Instead of Void we will write HttpResponseMessage,


As you can see from the above code we had used HttpResponseMessage instead of void and we had taken a variable which is message and in that whatever response is coming attached to a property called as created response and in that we are passing those HTTP status codes in that parameter.

Now we want to include status 201 which is the location of the newly created URI  -- to do that we will use message object,
  1. public HttpResponseMessage post ([FromBody]employeesData employee)  
  2. {  
  3.     try  
  4.     {  
  5.         using (TESTEntities entities = new TESTEntities())  
  6.         {  
  7.             entities.employeesDatas.Add(employee);  
  8.             entities.SaveChanges();  
  9.             var message = Request.CreateResponse(HttpStatusCode.Created, employee);  
  10.             message.Headers.Location = new Uri(Request.RequestUri + employee.ID.ToString());  
  11.             return message;  
  12.         }  
  13.     }  
  14.     catch (Exception ex)  
  15.     {  
  16.         return Request.CreateErrorResponse(HttpStatusCode.BadRequest,ex);  
  17.     }
  18. }  
We had created message Header and location property and in that we will be concating that URI to which the respective ID been created. We had included try catch, in catch we will be monitoring for Bad requests which are coming from HTTP. Now save the changes and reload the app and let’s issue a request from fiddler.



I had created another JSON data to execute this,

Now to SQL and see data,



As you can see from the data we had successfully inserted our data. Notice here the id is seven for a newly-created employee. Now let’s go to fiddler and let’s inspect the response we had got --  we will see,



Notice with the response code, the status code is 201 created and you can see the location as well URI of the newly created item as well. So copy that header value as



Paste the header value in the URL click on the URL



When you hit enter we got the newly created URI entities as expected. Now we will modify the GET method as well. First we write code for an employee whose id doesn’t exist in the database.

So in the fiddler we will specify an id that does not exist as,



So let’s execute this request



As you can see, we got the JSON which is NULL because we don’t have the id of that employee which is requested.

Now, this is misleading, according to the standard of REST when an item is not found we should be actually returning status code 404 which stands for Not Found. Let’s see how to achieve this let’s flip to VS and we will modify the implementation of GET method 
  1. public HttpResponseMessage Get(int id)    
  2. {    
  3.     using (TESTEntities entities = new TESTEntities())    
  4.     {    
  5.         var entity=  entities.employeesDatas.FirstOrDefault(e => e.ID == id);    
  6.         if (entity != null)    
  7.         {    
  8.             return Request.CreateResponse(HttpStatusCode.OK, entity);    
  9.         }    
  10.         else    
  11.         {    
  12.             return Request.CreateErrorResponse(HttpStatusCode.NotFound,"Employee With id = " + id.ToString() + " not found");    
  13.         }  
  14.     }  
  15. }  
So, here we have modified our GET method here we had used a condition if entity is not null it will return a status code null;  then, it will return not found. Now, let’s run the app,



Notice, now we have got 404 Not Found,



And look at the message we have got the employee with that ID is not found.

Now, if we request with an employee id that does exist we will see.



Now, here we see the status code 200 OK and the data we had requested.



Points to remember, 
  • If a method type is void, by default status code is 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 ID doesn’t exist.


Similar Articles