How To Create ASP.NET Web API GET, POST, PUT, and DELETE

Introduction

This article will demonstrate how to create an ASP.NET API to perform CRUD operations. We will create a new Web API project and implement GET, POST, PUT and DELETE methods for a CRUD operation using Entity Framework. ASP.NET Web API is an extensible framework for building HTTP-based services that can be accessed in different applications on different platforms such as web, windows, mobile etc.

Step 1
 
Open SQL Server 2014 (or the version of your choice) and create a table and insert some records.
  1. CREATE TABLE [dbo].[Employee](  
  2.     [Employee_Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [First_Name] [nvarchar](50) NULL,  
  4.     [Last_Name] [nvarchar](50) NULL,  
  5.     [Salary] [money] NULL,  
  6.     [Joing_Date] [nvarchar](50) NULL,  
  7.     [Department] [nvarchar](50) NULL,  
  8.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [Employee_Id] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  12. ) ON [PRIMARY]  
  13.   
  14. GO  

Step 2

Open Visual Studio 2017, click on New Project, and create an empty Web API application project.

Screenshot for creating new project 1

ASP.NET Web API GET, POST, PUT and DELETE

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in below screenshot.

Screenshot for creating new project 2

ASP.NET Web API GET, POST, PUT and DELETE

After clicking on OK one more window will appear; choose empty, check on Web API checkbox then click on OK as shown in the below screenshot.

Screenshot for creating new project 3

ASP.NET Web API GET, POST, PUT and DELETE

After clicking OK, the project will be created with the name of WebAPICURD_Demo.

Step 3

Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

Screenshot for adding entity framework 1

ASP.NET Web API GET, POST, PUT and DELETE 

After clicking on the New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory you can give any name) and click on Add.

Screenshot for adding entity framework 2

ASP.NET Web API GET, POST, PUT and DELETE 

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next.

Screenshot for adding entity framework 3

ASP.NET Web API GET, POST, PUT and DELETE 

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter dot (.). Choose your database and click on OK.

Screenshot for adding entity framework 4

ASP.NET Web API GET, POST, PUT and DELETE 

The connection will be added.  You can change the name of your connection below. It will save the connection in web config then click on Next.

Screenshot for adding entity framework 5

ASP.NET Web API GET, POST, PUT and DELETE 

After clicking on NEXT another window will appear; choose database table name as shown in the below screenshot then click on Finish.

Entity framework will be added and respective class gets generated under the Models folder.

Screenshot for adding entity framework 6

ASP.NET Web API GET, POST, PUT and DELETE 

Following class will be added,

  1. namespace WebAPICURD_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Employee  
  7.     {  
  8.         public int Employee_Id { get; set; }  
  9.         public string First_Name { get; set; }  
  10.         public string Last_Name { get; set; }  
  11.         public Nullable<decimal> Salary { get; set; }  
  12.         public string Joing_Date { get; set; }  
  13.         public string Department { get; set; }  
  14.     }  
  15. }  

Step 4

Right click on Controllers folder, select Add, then choose Controller as shown in the below screenshot.

Screenshot 1

ASP.NET Web API GET, POST, PUT and DELETE 

After clicking on the controller, a window will appear. Choose Web API 2 Controller-Empty and click on Add.

 ASP.NET Web API GET, POST, PUT and DELETE

After clicking on Add another window will appear with DefaultController. Change the name to EmployeeController then click on Add. EmployeeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.

 ASP.NET Web API GET, POST, PUT and DELETE

Complete code for API controller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using WebAPICURD_Demo.Models;  
  8.   
  9. namespace WebAPICURD_Demo.Controllers  
  10. {  
  11.     public class EmployeeController : ApiController  
  12.     {  
  13.         public IEnumerable<Employee> GetEmployees()  
  14.         {  
  15.             using (EmployeeEntities db=new EmployeeEntities())  
  16.             {  
  17.                 return db.Employees.ToList();  
  18.             }  
  19.         }  
  20.         public HttpResponseMessage GetEmployeeById(int id)  
  21.         {  
  22.             using (EmployeeEntities db=new EmployeeEntities())  
  23.             {  
  24.                 var entity = db.Employees.FirstOrDefault(e => e.Employee_Id == id);  
  25.                 if (entity == null)  
  26.                 {  
  27.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id=" + id.ToString() + " not found");  
  28.                 }  
  29.                 else  
  30.                 {  
  31.                     return Request.CreateResponse(HttpStatusCode.OK,entity);  
  32.                 }  
  33.             }  
  34.         }  
  35.         public HttpResponseMessage Post([FromBody]Employee employee)  
  36.         {  
  37.             try  
  38.             {  
  39.                 using (EmployeeEntities db = new EmployeeEntities())  
  40.                 {  
  41.                     db.Employees.Add(employee);  
  42.                     db.SaveChanges();  
  43.                     var message = Request.CreateResponse(HttpStatusCode.Created, employee);  
  44.                     message.Headers.Location = new Uri(Request.RequestUri + employee.Employee_Id.ToString());  
  45.                     return message;  
  46.                 }  
  47.             }  
  48.             catch (Exception ex)  
  49.             {  
  50.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  51.             }  
  52.         }  
  53.         public HttpResponseMessage Delete(int id)  
  54.         {  
  55.             using (EmployeeEntities db = new EmployeeEntities())  
  56.             {  
  57.                 var entity = db.Employees.FirstOrDefault(e => e.Employee_Id == id);  
  58.                 if (entity == null)  
  59.                 {  
  60.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id=" + id.ToString() + "not found to delete");  
  61.                 }  
  62.                 else  
  63.                 {  
  64.                     db.Employees.Remove(entity);  
  65.                     db.SaveChanges();  
  66.                     return Request.CreateResponse(HttpStatusCode.OK);  
  67.                 }  
  68.             }  
  69.         }  
  70.         public HttpResponseMessage Put(int id, [FromBody]Employee employee)  
  71.         {  
  72.             using (EmployeeEntities db = new EmployeeEntities())  
  73.             {  
  74.                 try  
  75.                 {  
  76.                     var entity = db.Employees.FirstOrDefault(e => e.Employee_Id == id);  
  77.                     if (entity == null)  
  78.                     {  
  79.                         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id=" + id.ToString() + "not found to update");  
  80.                     }  
  81.                     else  
  82.                     {  
  83.                         entity.First_Name = employee.First_Name;  
  84.                         entity.Last_Name = employee.Last_Name;  
  85.                         entity.Salary = employee.Salary;  
  86.                         entity.Joing_Date = employee.Joing_Date;  
  87.                         entity.Department = employee.Department;  
  88.                         db.SaveChanges();  
  89.                         return Request.CreateResponse(HttpStatusCode.OK, entity);  
  90.                     }  
  91.                 }  
  92.                 catch (Exception ex)  
  93.                 {  
  94.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  95.                 }  
  96.             }  
  97.         }  
  98.     }  
  99. }  

Step 5

Build project and run project by pressing ctrl+F5

URL

portnumeber/api/controllerName

Output

ASP.NET Web API GET, POST, PUT and DELETE

URL

portnumeber/api/controllerName/id (search customer by id)

Output

Output
Conclusion

I have created an ASP.NET Web API to perform GET, POST, PUT, and DELETE operations. It has been tested on Fiddler. I hope this will be helpful for beginners.


Similar Articles