Creating POST method in Web API using .Net

Web API is a programming interface which exposes endpoints that define request and response eco system. Each method can contain in different types of request like POST, GET, PUT, DELETE etc. request should be based the way which the API is built.

Here Is the simple example to create simple POST method that inserts some data into database using Entity framework.

1.      Create new Project with WEB API as below

This will create the new project of WEBAPI in MVC framework.

2.      Right Click on the controllers and add new WEB API Controller as shown below.

           Name your WEB API controller accordingly, I have named it as EmployeeController.

   3.      Right click on the Model folder and add ADO.NET Entity Data Model as shown below.

Entity Data Model wizard asks you to select what the model should contain, Select EF designer from Database as shown below.

Click on Next and Choose Data Connection by selecting new connection.

After Clicking New Connection, it will prompt the new popup to enter server details, userid, password and selecting the database.

After test connection is successful click on OK and your connection string will get generated as shown below

Select the Entity framework version and Click the Next button 

     Select the Table that is necessary for accessing the data as shown below.



         Click on Finish that will generate the EDMX file with table name and columns as shown below.

4.      On EmployeeController.cs we can find multiple functions remove all the except POST  method and replace the code as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FirstWebApiDemo.Models;

namespace FirstWebApiDemo.Controllers
    public class EmployeeController : ApiController
        public HttpResponseMessage Post([FromBody]EmployeeDetail employee)
                using (ACT2_MINIQEntities entities = new ACT2_MINIQEntities())
                    entities.SaveChanges(); //inserts data in to DB
                    var message = Request.CreateResponse(HttpStatusCode.Created, employee); //Setting Response Headers
                    return message; //Returns Http Response
            catch (Exception exception)
                //handling Exceptions
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, exception);

To Test Output Use Fiddler Or POSTMAN Rest-client.

Output :