How to use POST method in WEB-API using MVC 4.0 ?

Are you new to concepts of WEB-API in MVC 4.0? This code will guide you how to write POST method in web api. Web API provides many new features now and makes many scenarios much easier You can post your queries here incase you have. It would be great to help you.

Concept: POST method is used to write data into tables of database.
You have to use WEB-API template which will be used as intermediate between client application i.e. internet application and server.
I haved used Razor engine at the time of creating MVC 4.0 application.
Disadvantage of .edmx file Everytime when you update your model, you have to update .edmx which is mandatory activity.
Alternative for .edmx file If you do not want to use .edmx then you can use data transfer object which is nothing but DTO.
This way, your model classes won't be exposed to the client.

public HttpResponseMessage Post(tablename tblObj)
if (ModelState.IsValid)
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, tblObj);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = tblObj.columnname }));
return response;
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error found.");

db.SaveChanges() is used to save data into database. It will generate HttpResponseMessage after execution. HttpStatusCode is returned based on success or failure.
How to test the code?
You can test this code by either checking tables data and see newly added data is present in the table or not. Second way is to test this code by using any web debugging tool for e.g. Fiddler.
JSON is created in fiddler which can be viewed.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: