Restful API In ASP.NET: Introduction of REST & Web API

In the previous article Getting Started in Web API, we have learned the basic infrastructure of API and multiple clients which can consume API. Now, we will discuss here the architecture of Restful API and we will also get an overview of ASP.NET Web API introduction.

What is REST


REST is the acronym that stands for: Representational State Transfer. REST is an architectural style of distributed system. It is based upon the set of principles that describes how network resources are defined and addressed. These set of principles was first described by “Roy Fielding” in 2000. REST is bigger than Web Services.

RESTful services uses HTTP (Hyper Text Transfer Protocol) to communicate. REST system interface with external systems as web resources identified by URIs (Uniform Resource Identifiers).

Constraints of REST


A Restful system should follow the constrains so it can be called Restful. There are 5 and 1 optional constraints of REST.

api

HTTP Verbs


Http verbs plays a very important role in the Restful Web API. The most common Http verbs are GET, PUT, POST and DELETE and these correspond to CRUD (Create, Read, Update and Delete) operations respectively.

The following Http Verbs exists:

  • Get
  • Post
  • Put
  • Delete
  • Trace
  • Options
  • Connect
  • Patch

I will discuss here the most common used verbs and we will also see that how we can use these verbs in my next articles in which we will perform database operations with the help of the above Http verbs.

So, the following are the description of most common used Http verbs:

GET

As the name specifies, this verb is used to retrieve the data or information. It does not have any other effect except getting data.

Syntax

[HttpGet]

We can use the above syntax to define the method as a GET method. If we are retrieving the data from the database or displaying the data, then we can use this attribute to get the data.

Use

Let’s see an example of a GET method:

  1. [HttpGet, ActionName("GetInfo")]  
  2. public HttpResponseMessage GetInfo()  
  3. {  
  4.     //functional requirements  
  5. }  
In the above example there is a method named GetInfo which is defined as GET method. ActionName attribute is used to define the name of an action method.

Call

http://localhost:56828/api/sample/GetInfo

By the help of above Requested URI, we can get the information. Sample is the controller name.

POST

This verb is used to generate or create the resource. For example, If we have to add some information to the database then we must define the method as a POST method. The most common form to submit the data into the POST method is to pass the data into any entity object.

Syntax

[HttpPost]

We can use the above syntax to define the method as a POST method.

Use
  1. [HttpPost, ActionName("PostInfo")]  
  2. public HttpResponseMessage PostInfo(Result result)   
  3. {  
  4.     //functional requirements  
  5. }  
In the above example there is a method named PostInfo which is defined as POST method. We have to assign the data to the properties of the entity (Result class).

PUT

This verb is used to update the existing resource. For example, If we have to update some information to the database then we can define the method as a PUT method. We can send the data in the form of object as well as in a parameter too.

Syntax

[HttpPut]

We can use the above syntax to define the method as a PUT method.

Use
  1. [HttpPut, ActionName("UpdateInfo")]  
  2. public HttpResponseMessage UpdateInfo(Result result)  
  3. {  
  4.     //functional requirements  
  5. }  
In the above example there is a method as named UpdateInfo which is defined as PUT method. We can assign the id to update the info.

DELETE

This verb is used to delete the existing resource. For example, If we have to delete some information to the database then we can define the method as a DELETE method. We can send the data in the form of object as well as in a parameter too.

Syntax

[HttpDelete]

We can use the above syntax to define the method as a DELETE method.

Use
  1. [HttpDelete, ActionName("DeleteInfo")]  
  2. public HttpResponseMessage DeleteInfo(int UserId)  
  3. {  
  4.     //functional requirements  
  5. }  
In the above example there is a method named DeleteInfo which is defined as DELETE method. We can assign the id to delete the info.

Demo

In the above section you have learned all the basics of RESTtful architecture and Web API. Now, in this section we will create the demo application in which we will perform the database operations from the ASP.NET Web API Application.

Prerequisites

If you want to create the demo then you must have Visual Studio 2012 or later version to do this. I am using here Visual Studio 2015.

Getting Started

Let’s create an ASP.NET Web API app in which we will perform the CRUD operations and later we will publish it into the Azure API. Now, just follow the procedure below to create the application.

Creating Web API Application


In this section, we will create the ASP.NET Web API application by following the steps below:

Step 1: Open the Visual Studio as an Administrator and click on “New Project”.

Visual Studio Start Page
                                       Figure 1: Visual Studio Start Page

Step 2: Select the Web tab from the left pane and then select ASP.NET Web Application to create the project.

Creating New Application
                                                 Figure 2: Creating New Application

Step 3: In the next ASP.NET wizard select the Web API Project Template.

Web API Project Template
                                                   Figure 3: Web API Project Template

Now, Web API application is created successfully.

Perform Database Operations

In this section, we’ll perform database operation in which we will create the stored procedures to perform CRUD operations. I have created the database and tables with the record and stored procedures too. You can create the whole database from the following script or you can create your own database records. So, just follow the steps below:

Step 1: Just create the database from the following script:

CREATE DATABASE [Cricketer]


Step 2: Now from the following script the whole database is created with the tables and records and stored procs:
  1. USE [Cricketer]  
  2. GO  
  3. /****** Object: StoredProcedure [dbo].[CC_GetCricketerList] Script Date: 1/31/2016 8:50:44 PM ******/  
  4. IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_GetCricketerList]') AND type in (N 'P', N 'PC'))  
  5. DROP PROCEDURE[dbo].[CC_GetCricketerList]  
  6. GO  
  7. /****** Object: StoredProcedure [dbo].[CC_GetCricketerDetailsById] Script Date: 1/31/2016 8:50:44 PM ******/  
  8. IF EXISTS(SELECT * FROMsys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_GetCricketerDetailsById]') AND type in (N 'P', N 'PC'))  
  9. DROP PROCEDURE[dbo].[CC_GetCricketerDetailsById]  
  10. GO  
  11. /****** Object: StoredProcedure [dbo].[CC_DeleteCricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/  
  12. IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_DeleteCricketerProfile]') AND type in(N 'P', N 'PC'))  
  13. DROP PROCEDURE[dbo].[CC_DeleteCricketerProfile]  
  14. GO  
  15. /****** Object: StoredProcedure [dbo].[CC_AddUpdateCricketerDetails] Script Date: 1/31/2016 8:50:44 PM ******/  
  16. IF EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_AddUpdateCricketerDetails]') AND type in (N 'P', N 'PC'))  
  17. DROP PROCEDURE[dbo].[CC_AddUpdateCricketerDetails]  
  18. GO  
  19. /****** Object: Table [dbo].[CricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/  
  20. IF EXISTS(SELECT * FRO Msys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CricketerProfile]') AND typei n(N 'U'))  
  21. DROP TABLE[dbo].[CricketerProfile]  
  22. GO  
  23. /****** Object: Table [dbo].[CricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/  
  24. SET ANSI_NULLS ON  
  25. GO  
  26. SET QUOTED_IDENTIFIER ON  
  27. GO  
  28. SET ANSI_PADDING ON  
  29. GO  
  30. IF NOT EXISTS(SELECT * FROM sys.objects WHEREobject_id = OBJECT_ID(N '[dbo].[CricketerProfile]') AND type in (N 'U'))  
  31. BEGIN  
  32. CREATE TABLE[dbo].[CricketerProfile](  
  33.     [ID][int] IDENTITY(1, 1) NOT NULL, [Name][varchar](50) NULL, [ODI][intNULL, [Tests][intNULL, [ODIRuns][intNULL, [TestRuns][intNULL,  
  34.     CONSTRAINT[PK_CricketerProfile] PRIMARYKEYCLUSTERED(  
  35.         [ID] ASC  
  36.     ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON[PRIMARY]  
  37. ON[PRIMARY]  
  38. END  
  39. GO  
  40. SET ANSI_PADDING OFF  
  41. GO  
  42. SET IDENTITY_INSERT[dbo].[CricketerProfile] ON  
  43.   
  44. GO  
  45. INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(1, N 'Sachin Tendulkar', 463, 200, 18426, 15921)  
  46. GO  
  47. INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(2, N 'Saurav Ganguly', 311, 113, 11363, 7212)  
  48. GO  
  49. INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(3, N 'Rahul Dravid', 344, 164, 10889, 13228)  
  50. GO  
  51. INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(4, N 'V.V.S. Laxman', 86, 134, 2338, 8781)  
  52. GO  
  53. INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(5, N 'Virendar Sehwag', 251, 104, 8273, 8586)  
  54. GO  
  55. SET IDENTITY_INSERT[dbo].[CricketerProfile] OFF  
  56. GO  
  57. /****** Object: StoredProcedure [dbo].[CC_AddUpdateCricketerDetails] Script Date: 1/31/2016 8:50:45 PM ******/  
  58. SET ANSI_NULLS ON  
  59. GO  
  60. SET QUOTED_IDENTIFIER ON  
  61. GO  
  62. IF NOT EXISTS(SELECT * FROM sys.objects WHEREobject_id = OBJECT_ID(N '[dbo].[CC_AddUpdateCricketerDetails]') AND type in(N 'P', N 'PC'))  
  63. BEGIN  
  64. EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_AddUpdateCricketerDetails] AS'  
  65. END  
  66. GO  
  67. -- === === === === === === === === === === === === === === ===  
  68. --Author: Nimit Joshi  
  69.     --Create date: 31 / 01 / 2016  
  70.     --Description: This sp is used to insert and update data in Cricketer Profile  
  71.     -- === === === === === === === === === === === === === === ===  
  72.     ALTERPROCEDURE CC_AddUpdateCricketerDetails  
  73.     --Add the parameters  
  74. for the stored procedure here  
  75. @Id INT = NULL,  
  76.     @Name VARCHAR(50),  
  77.     @ODI INT = NULL,  
  78.     @Tests INT = NULL,  
  79.     @OdiRuns INT = NULL,  
  80.     @TestRuns INT = NULL,  
  81.     @Type INT--1  
  82. for Add Record and 2  
  83. for Update Record  
  84. @Status INTOUT  
  85. AS  
  86. BEGIN  
  87. --SET NOCOUNT ON added to prevent extra result sets from  
  88. --interfering with SELECT statements.  
  89.   
  90. IF(@Type = 1)  
  91. BEGIN  
  92. IF NOT EXISTS(SELECT cp.Name FROM dbo.CricketerProfile(NOLOCK) cp WHERE cp.Name LIKE '%' + @Name + '%')  
  93. BEGIN  
  94. INSERT INTO dbo.CricketerProfile
  95. (
  96.     Name,  
  97.     ODI,  
  98.     Tests,  
  99.     ODIRuns,  
  100.     TestRuns  
  101. )  
  102. VALUES(@Name--Name - varchar(50) @ODI, --ODI - int @Tests, --Tests - int @OdiRuns, --ODIRuns - int @TestRuns--TestRuns - int);  
  103. IF(@ @ROWCOUNT > 0)  
  104. BEGIN  
  105. SET @Status = 1;  
  106. --Record inseted successfully!!  
  107.     END;  
  108. END;  
  109. ELSE  
  110. BEGIN  
  111. SET @Status = 2;  
  112. --Record alredy exists!!  
  113.     END;  
  114. END;  
  115. ELSE  
  116. IF(@Type = 2)  
  117. BEGIN  
  118. IF EXISTS(SELECT ccp.ID FROM dbo.CricketerProfile ccp(NOLOCK) WHERE ccp.ID = @Id)  
  119. BEGIN  
  120. UPDATE dbo.CricketerProfile  
  121. SET Name = ISNULL(@NameName),  
  122.     ODI = ISNULL(@ODI, ODI),  
  123.     Tests = ISNULL(@Tests, Tests),  
  124.     ODIRuns = ISNULL(@OdiRuns, ODIRuns),  
  125.     TestRuns = ISNULL(@TestRuns, TestRuns)  
  126. WHERE ID = @Id;  
  127. IF(@ @ROWCOUNT > 0)  
  128. BEGIN  
  129. SET @Status = 3;  
  130. --Record Updated Successfully!!  
  131.     END;  
  132. END;  
  133. ELSE  
  134. BEGIN  
  135. SET @Status = 4;  
  136. --Record does not exists!!  
  137.     END;  
  138. END;  
  139. END;  
  140. GO  
  141. /****** Object: StoredProcedure [dbo].[CC_DeleteCricketerProfile] Script Date: 1/31/2016 8:50:45 PM ******/  
  142. SET ANSI_NULLS ON  
  143. GO  
  144. SET QUOTED_IDENTIFIER ON  
  145. GO  
  146. IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_DeleteCricketerProfile]') AND type in(N 'P', N 'PC'))  
  147. BEGIN  
  148. EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_DeleteCricketerProfile] AS'  
  149. END  
  150. GO  
  151. -- === === === === === === === === === === === === === === ===  
  152. --Author: Nimit Joshi  
  153.     --Create date: 31 / 01 / 2016  
  154.     --Description: This sp is used to delete the records from the cricketer table.  
  155.     -- === === === === === === === === === === === === === === ===  
  156.     ALTER PROCEDURE[dbo].[CC_DeleteCricketerProfile]  
  157.     --Add the parameters  
  158. for the stored procedure here  
  159. @Id INT, @Status INTOUT  
  160. AS  
  161. BEGIN  
  162. --SET NOCOUNT ON added to prevent extra result sets from  
  163. --interfering with SELECT statements.  
  164. IF EXISTS(SELECT cp.ID FROM dbo.CricketerProfile cp(NOLOCK) WHERE cp.ID = @Id)  
  165. BEGIN  
  166. DELETE FROM dbo.CricketerProfile  
  167. WHERE ID = @Id;  
  168. IF(@ @ROWCOUNT > 0)  
  169. BEGIN  
  170. SET @Status = 1;  
  171. --Deleted Successfully!!  
  172.     END;  
  173. END;  
  174. ELSE  
  175. BEGIN  
  176. SET @Status = 2;  
  177. --Record doesn 't exists  
  178. END;  
  179. END;  
  180.   
  181. GO  
  182. /****** Object: StoredProcedure [dbo].[CC_GetCricketerDetailsById] Script Date: 1/31/2016 8:50:45 PM ******/  
  183. SET ANSI_NULLSON  
  184. GO  
  185. SET QUOTED_IDENTIFIERON  
  186. GO  
  187. IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_GetCricketerDetailsById]') AND type in(N 'P', N 'PC'))  
  188. BEGIN  
  189. EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_GetCricketerDetailsById] AS'  
  190. END  
  191. GO  
  192. ALTER Proc[dbo].[CC_GetCricketerDetailsById]  
  193. @ID int  
  194. AS  
  195. Begin  
  196. select * from CricketerProfile(NOLOCK) where ID = @Id  
  197. End  
  198.   
  199. GO  
  200. /****** Object: StoredProcedure [dbo].[CC_GetCricketerList] Script Date: 1/31/2016 8:50:45 PM ******/  
  201. SET ANSI_NULLS ON  
  202. GO  
  203. SET QUOTED_IDENTIFIER ON  
  204. GO  
  205. IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[CC_GetCricketerList]') AND type in(N 'P', N 'PC'))  
  206. BEGIN  
  207. EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_GetCricketerList] AS'  
  208. END  
  209. GO  
  210. ALTER VProc[dbo].[CC_GetCricketerList]  
  211. AS  
  212. Begin  
  213. select ID, Name from CricketerProfile(NOLOCK)  
  214. End  
  215. GO  
Perform CRUD Operations

In this section we will add new projects to associate the database with the Web API application. So, start with the following steps:

Step 1: Just add a new Solution Folder in your application named “Models”

Adding New Solution Folder
                                     Figure 4: Adding New Solution Folder

Step 2: Add a “New Project” in the Models folder

Adding New Project
                                                  Figure 5: Adding New Project

Step 3: Select Class Library template to add a new project and name it “BestCricketers.Models”.

Adding Class Library
                                                 Figure 6: Adding Class Library

Step 4: Add a new class named “CricketerProfile” and replace the code with the following code:
  1. public class CricketerProfile: Result  
  2. {  
  3.     public int Id   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Name   
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public int ODI  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public int Tests  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public int OdiRuns   
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public int TestRuns  
  29.     {  
  30.         get;  
  31.         set;  
  32.     }  
  33.     public int Type   
  34.     {  
  35.         get;  
  36.         set;  
  37.     }  
  38. }  
  39.   
  40. public class Result   
  41. {  
  42.     public int Status   
  43.     {  
  44.         get;  
  45.         set;  
  46.     }  
  47.     public string Message   
  48.     {  
  49.         get;  
  50.         set;  
  51.     }  
  52. }  
Step 5: Now add another Solution Folder named “Infrastructure” and add a new project named “BestCricketers.Core”. Add two new folders “BL” and “DAL” in this project.

Step 6: Now add “Enterprise Library” Nuget Package,

Adding Enterprise Library Package
                              Figure 7: Adding Enterprise Library Package

Step 7: Add a new class “CricketerDAL” in the DAL folder and replace the code with the following code:
  1. namespace BestCricketers.Core.DAL {  
  2.     public class CricketerDAL {  
  3.         #region Variable  
  4.         ///<summary>  
  5.         /// Specify the Database variable    
  6.         ///</summary>  
  7.         Database objDB;  
  8.         ///<summary>  
  9.         /// Specify the static variable    
  10.         ///</summary>  
  11.         static string ConnectionString;#  
  12.         endregion# region Constructor  
  13.         ///<summary>  
  14.         /// This constructor is used to get the connectionstring from the config file      
  15.         ///</summary>  
  16.         public CricketerDAL() {  
  17.             ConnectionString = ConfigurationManager.ConnectionStrings["CricketerConnectionString"].ToString();  
  18.         }  
  19.         #endregion  
  20.         #region Database Method  
  21.         public List < T > ConvertTo < T > (DataTable datatable) where T: new() {  
  22.             List < T > Temp = newList < T > ();  
  23.             try {  
  24.                 List < string > columnsNames = newList < string > ();  
  25.                 foreach(DataColumn DataColumn in datatable.Columns)  
  26.                 columnsNames.Add(DataColumn.ColumnName);  
  27.                 Temp = datatable.AsEnumerable().ToList().ConvertAll < T > (row => getObject < T > (row, columnsNames));  
  28.                 return Temp;  
  29.             }   
  30.             catch {  
  31.                 return Temp;  
  32.             }  
  33.         }  
  34.         public T getObject < T > (DataRow row, List < string > columnsName) whereT: new() {  
  35.             T obj = newT();  
  36.             try {  
  37.                 string columnname = "";  
  38.                 string value = "";  
  39.                 PropertyInfo[] Properties;  
  40.                 Properties = typeof (T).GetProperties();  
  41.                 foreach(PropertyInfo objProperty in Properties) {  
  42.                     columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());  
  43.                     if (!string.IsNullOrEmpty(columnname)) {  
  44.                         value = row[columnname].ToString();  
  45.                         if (!string.IsNullOrEmpty(value)) {  
  46.                             if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) {  
  47.                                 value = row[columnname].ToString().Replace("$""").Replace(",""");  
  48.                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);  
  49.                             } else {  
  50.                                 value = row[columnname].ToString();  
  51.                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);  
  52.                             }  
  53.                         }  
  54.                     }  
  55.                 }  
  56.                 return obj;  
  57.             }   
  58.             catch (Exception ex) {  
  59.                 return obj;  
  60.             }  
  61.         }  
  62.         #endregion  
  63.         #region CricketerProfile  
  64.         ///<summary>  
  65.         /// This method is used to get the cricketer data      
  66.         ///</summary>  
  67.         ///<returns></returns>  
  68.         public List < CricketerProfile > GetCricketerList() {  
  69.             List < CricketerProfile > objGetCricketers = null;  
  70.             objDB = newSqlDatabase(ConnectionString);  
  71.             using(DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerList")) {  
  72.                 try {  
  73.                     using(DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0]) {  
  74.                         objGetCricketers = ConvertTo < CricketerProfile > (dataTable);  
  75.                     }  
  76.                 }   
  77.                 catch (Exception ex) {  
  78.                     throw ex;  
  79.                     returnnull;  
  80.                 }  
  81.             }  
  82.             return objGetCricketers;  
  83.         }  
  84.         ///<summary>  
  85.         /// This method is used to get cricketers details by cricketer id    
  86.         ///</summary>  
  87.         ///<returns></returns>  
  88.         public List < CricketerProfile > GetCricketerDetailsById(int Id) {  
  89.             List < CricketerProfile > objCricketerDetails = null;  
  90.             objDB = newSqlDatabase(ConnectionString);  
  91.             using(DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerDetailsById")) {  
  92.                 try {  
  93.                     objDB.AddInParameter(objcmd, "@ID", DbType.Int32, Id);  
  94.                     using(DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0]) {  
  95.                         objCricketerDetails = ConvertTo < CricketerProfile > (dataTable);  
  96.                     }  
  97.                 }   
  98.                 catch (Exception ex) {  
  99.                     throw ex;  
  100.                     returnnull;  
  101.                 }  
  102.             }  
  103.             return objCricketerDetails;  
  104.         }  
  105.         ///<summary>  
  106.         /// This method is used to add update cricketer info  
  107.         ///</summary>  
  108.         ///<param name="cricketer"></param>  
  109.         ///<returns></returns>  
  110.         public int AddUpdateCricketerInfo(CricketerProfile cricketer) {  
  111.             int result = 0;  
  112.             objDB = newSqlDatabase(ConnectionString);  
  113.             using(DbCommand objCMD = objDB.GetStoredProcCommand("CC_AddUpdateCricketerDetails")) {  
  114.                 objDB.AddInParameter(objCMD, "@Id", DbType.Int32, cricketer.Id);  
  115.                 if (string.IsNullOrEmpty(cricketer.Name)) objDB.AddInParameter(objCMD, "@Name", DbType.String, DBNull.Value);  
  116.                 else objDB.AddInParameter(objCMD, "@Name", DbType.String, cricketer.Name);  
  117.                 if (cricketer.ODI == 0) objDB.AddInParameter(objCMD, "@ODI", DbType.Int32, DBNull.Value);  
  118.                 else objDB.AddInParameter(objCMD, "@ODI", DbType.Int32, cricketer.ODI);  
  119.                 if (cricketer.Tests == 0) objDB.AddInParameter(objCMD, "@Tests", DbType.Int32, DBNull.Value);  
  120.                 else objDB.AddInParameter(objCMD, "@Tests", DbType.Int32, cricketer.Tests);  
  121.                 if (cricketer.OdiRuns == 0) objDB.AddInParameter(objCMD, "@OdiRuns", DbType.Int32, DBNull.Value);  
  122.                 else objDB.AddInParameter(objCMD, "@OdiRuns", DbType.Int32, cricketer.OdiRuns);  
  123.                 if (cricketer.TestRuns == 0) objDB.AddInParameter(objCMD, "@TestRuns", DbType.Int32, DBNull.Value);  
  124.                 else objDB.AddInParameter(objCMD, "@TestRuns", DbType.Int32, cricketer.TestRuns);  
  125.                 objDB.AddInParameter(objCMD, "@Type", DbType.Int32, cricketer.Type);  
  126.                 objDB.AddOutParameter(objCMD, "@Status", DbType.Int16, 0);  
  127.                 try {  
  128.                     objDB.ExecuteNonQuery(objCMD);  
  129.                     result = Convert.ToInt32(objDB.GetParameterValue(objCMD, "@Status"));  
  130.                 }   
  131.                 catch (Exception) {  
  132.                     throw;  
  133.                 }  
  134.             }  
  135.             return result;  
  136.         }  
  137.         ///<summary>  
  138.         /// This method is used to delete cricketer info  
  139.         ///</summary>  
  140.         ///<param name="cricketer"></param>  
  141.         ///<returns></returns>  
  142.         public int DeleteCricketerInfo(CricketerProfile cricketer) {  
  143.             int result = 0;  
  144.             objDB = newSqlDatabase(ConnectionString);  
  145.             using(DbCommand objCMD = objDB.GetStoredProcCommand("CC_DeleteCricketerProfile")) {  
  146.                 objDB.AddInParameter(objCMD, "@Id", DbType.Int32, cricketer.Id);  
  147.                 objDB.AddOutParameter(objCMD, "@Status", DbType.Int16, 0);  
  148.                 try {  
  149.                     objDB.ExecuteNonQuery(objCMD);  
  150.                     result = Convert.ToInt32(objDB.GetParameterValue(objCMD, "@Status"));  
  151.                 }   
  152.                 catch (Exception) {  
  153.                     throw;  
  154.                 }  
  155.             }  
  156.             return result;  
  157.         }  
  158.         #endregion  
  159.     }  
  160. }  
Step 8: Add a new class “CricketerBL” in the BL folder and replace the code with the following code:
  1. namespace BestCricketers.Core.BL {  
  2.     public class CricketerBL {  
  3.         ///<summary>  
  4.         /// This method is used to get the cricketer list  
  5.         ///</summary>  
  6.         ///<returns></returns>  
  7.         public List < CricketerProfile > GetCricketerList() {  
  8.             List < CricketerProfile > ObjCricketers = null;  
  9.             try {  
  10.                 ObjCricketers = newCricketerDAL().GetCricketerList();  
  11.             }  
  12.             catch (Exception) {  
  13.                 throw;  
  14.             }  
  15.             return ObjCricketers;  
  16.         }  
  17.         ///<summary>  
  18.         /// This method is used to get cricketers details by cricketer id    
  19.         ///</summary>  
  20.         ///<returns></returns>  
  21.         public List < CricketerProfile > GetCricketerDetailsById(int Id) {  
  22.             List < CricketerProfile > ObjCricketerDetails = null;  
  23.             try {  
  24.                 ObjCricketerDetails = newCricketerDAL().GetCricketerDetailsById(Id);  
  25.             }   
  26.             catch (Exception) {  
  27.                 throw;  
  28.             }  
  29.             return ObjCricketerDetails;  
  30.         }  
  31.         ///<summary>  
  32.         /// This method is used to add update cricketer info  
  33.         ///</summary>  
  34.         ///<param name="cricketer"></param>  
  35.         ///<returns></returns>  
  36.         public int AddUpdateCricketerInfo(CricketerProfile cricketer) {  
  37.             int result = 0;  
  38.             try {  
  39.                 result = newCricketerDAL().AddUpdateCricketerInfo(cricketer);  
  40.             }   
  41.             catch (Exception) {  
  42.                 return 0;  
  43.             }  
  44.             return result;  
  45.         }  
  46.         ///<summary>  
  47.         /// This method is used to delete cricketer info  
  48.         ///</summary>  
  49.         ///<param name="cricketer"></param>  
  50.         ///<returns></returns>  
  51.         public int DeleteCricketerInfo(CricketerProfile cricketer) {  
  52.             int result = 0;  
  53.             try {  
  54.                 result = newCricketerDAL().DeleteCricketerInfo(cricketer);  
  55.             } catch (Exception) {  
  56.                 return 0;  
  57.             }  
  58.             return result;  
  59.         }  
  60.     }  
  61. }  
Now our all methods are ready to perform operations.

Creating Web API

In this section, we will work on the ASP.NET Web API application. We will add the new Empty Web API Controller in which we will create some methods to call the CricketerBL class for performing the CRUD operations.

So, let’s begin with the following procedure:

Step 1: At first, in the API project, right click on the Controllers folder and goto Add, then click Controller,

control
                                               Figure 8: Adding New Controller

Step 2: Select the “Web API 2 Controller - Empty” in the next wizard

Add Scaffold Wizard
Figure 9: Add Scaffold Wizard

Step 3: Now enter the controller name as “CricketersController


Adding Controller
Figure 10: Adding Controller

Step 4: Add the following connection string in the “<ConnectionStrings>” tab in your “Web.config” file of the API project:
  1. <add    name="CricketerConnectionString"connectionString="Data Source=Your Server Name;Initial Catalog=Cricketer;User Id=Your User Id;Password=Your Password"providerName="System.Data.SqlClient" />  
Step 5: Now we will create methods and associate the Http verbs with them. As I said earlier, we will use the most common used verbs in here. So, start with the following sections:

Note:

Add the references of Core and Models project into the API project before adding methods in the API Controller.

GET

We will create two types of GET methods in here. In first method we will get the list of Cricketers and in the second method we will pass the CricketerId to get the cricketer details.

Now add the two GET methods with the following code:
  1. using BestCricketers.Core.BL;  
  2. using BestCricketers.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. namespace BestCricketers.Controllers {  
  9.     public class CricketersController: ApiController {  
  10.         #region Variable  
  11.         HttpResponseMessage response;  
  12.         CricketerBL cricketerBL;  
  13.         #endregion# region Public Method  
  14.         ///<summary>  
  15.         /// This method is used to get cricketer list  
  16.         ///</summary>  
  17.         ///<returns></returns>  
  18.         [HttpGet, ActionName("GetCricketerList")]  
  19.         public HttpResponseMessage GetCricketerList() {  
  20.             Result result;  
  21.             cricketerBL = newCricketerBL();  
  22.             try {  
  23.                 var cricketerList = cricketerBL.GetCricketerList();  
  24.                 if (!object.Equals(cricketerList, null)) {  
  25.                     response = Request.CreateResponse < List < CricketerProfile >> (HttpStatusCode.OK, cricketerList);  
  26.                 }  
  27.             }   
  28.             catch (Exception ex) {  
  29.                 result = newResult();  
  30.                 result.Status = 0;  
  31.                 result.Message = ex.Message;  
  32.                 response = Request.CreateResponse(HttpStatusCode.InternalServerError, result);  
  33.             }  
  34.             return response;  
  35.         }  
  36.         ///<summary>  
  37.         /// This method is used to get cricketer list by id  
  38.         ///</summary>  
  39.         ///<returns></returns>  
  40.         [HttpGet, ActionName("GetCricketerInfoById")]  
  41.         public HttpResponseMessage GetCricketerInfoById(int CricketerId) {  
  42.             Result result;  
  43.             cricketerBL = newCricketerBL();  
  44.             try {  
  45.                 var cricketerList = cricketerBL.GetCricketerDetailsById(CricketerId);  
  46.                 if (!object.Equals(cricketerList, null)) {  
  47.                     response = Request.CreateResponse < List < CricketerProfile >> (HttpStatusCode.OK, cricketerList);  
  48.                 }  
  49.             }   
  50.             catch (Exception ex) {  
  51.                 result = newResult();  
  52.                 result.Status = 0;  
  53.                 result.Message = ex.Message;  
  54.                 response = Request.CreateResponse(HttpStatusCode.InternalServerError, result);  
  55.             }  
  56.             return response;  
  57.         }#endregion  
  58.     }  
  59. }  
Application Execution

We have successfully created the Web API Controller. Now we will run this application and call our GET methods. We will use POSTMAN to call the GET methods which is easy to use. We can use the Fiddler too.

You can get the POSTMAN from here.

Step 1: Debug the application.

Step 2: Now open the POSTMAN and at first copy the url from the browser and use that url as I used in the following screenshot:

Call Url: http://localhost:64016/api/Cricketers/GetCricketerList,

Simple GET Call
                                                   Figure 11: Simple GET Call

Get Call with Parameter

Call Url: http://localhost:64016/api/Cricketers/GetCricketerInfoById?Cricketerid=1

Get Call with Parameter
                                         Figure 12: Get Call with Parameter

Now add the following three methods in the controller with which we can checkout the POST, PUT and DELETE methods :

POST

In this call, all the data will be send as an object. In POST call, data should be passed in the form of object and sometimes it depends on the condition and you can send the data in the form of FormData.

Here, I am sending the data in the form of object. So, let’s create the method for POST call with the following code:
  1. ///<summary>  
  2. /// This method is used to add cricketer info in the database.  
  3. ///</summary>  
  4. ///<returns></returns>  
  5. [HttpPost, ActionName("AddCricketerInfo")]  
  6. public HttpResponseMessage AddCricketerInfo(CricketerProfile Cricketer) {  
  7.     Result ObjResult;  
  8.     int result;  
  9.     cricketerBL = newCricketerBL();  
  10.     try {  
  11.         result = cricketerBL.AddUpdateCricketerInfo(Cricketer);  
  12.         if (result > 0) {  
  13.             if (result == 1) {  
  14.                 ObjResult = newResult();  
  15.                 ObjResult.Status = result;  
  16.                 ObjResult.Message = "Record Inserted Successfully!!";  
  17.                 response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);  
  18.             }  
  19.             elseif(result == 2) {  
  20.                 ObjResult = newResult();  
  21.                 ObjResult.Status = result;  
  22.                 ObjResult.Message = "Record Already Exists!!";  
  23.                 response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);  
  24.             }  
  25.             else {  
  26.                 ObjResult = newResult();  
  27.                 ObjResult.Status = result;  
  28.                 ObjResult.Message = "Record Not Added!!";  
  29.                 response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);  
  30.             }  
  31.         }  
  32.     }   
  33.     catch (Exception ex) {  
  34.         ObjResult = newResult();  
  35.         ObjResult.Status = 0;  
  36.         ObjResult.Message = ex.Message;  
  37.         response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);  
  38.     }  
  39.     return response;  
  40. }  
Step 3: Now open the POSTMAN and call the following url:

http://localhost:64016/api/Cricketers/AddCricketerInfo

At first add the Header as in the following screenshot:

Headers in POST Call
                                         Figure 13: Headers in POST Call

Now click on Send,

POST Call in Web API
                                                Figure 14: POST Call in Web API

In the above figure you can see your api is showing the response.

PUT

In this method we will add the method defined as HttpPut verb with which we can update the data. So, add the following code in the Controller:
  1. ///<summary>  
  2. /// This method is used to update cricketer info in the database.  
  3. ///</summary>  
  4. ///<param name="Cricketer"></param>  
  5. ///<returns></returns>  
  6. [HttpPut, ActionName("UpdateCricketerInfo")]  
  7. public HttpResponseMessage UpdateCricketerInfo(CricketerProfile Cricketer)  
  8. {  
  9.    Result ObjResult;  
  10.    int result;  
  11.        cricketerBL = newCricketerBL();  
  12.    try {  
  13.        result = cricketerBL.AddUpdateCricketerInfo(Cricketer);  
  14.   
  15.       if (result > 0)  
  16.       {  
  17.          if (result == 3)  
  18.          {  
  19.              ObjResult = newResult();  
  20.              ObjResult.Status = result;  
  21.              ObjResult.Message = "Record Updated Successfully!!";  
  22.              response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);  
  23.          }  
  24.          elseif (result == 2)  
  25.          {  
  26.               ObjResult = newResult();  
  27.               ObjResult.Status = result;  
  28.               ObjResult.Message = "Record does not Exists!!";  
  29.               response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);  
  30.          }  
  31.          else  
  32.          {  
  33.              ObjResult = newResult();  
  34.              ObjResult.Status = result;  
  35.              ObjResult.Message = "Record Not Added!!";  
  36.              response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);  
  37.          }  
  38.       }  
  39.    }  
  40.    catch (Exception ex)  
  41.    {  
  42.        ObjResult = newResult();  
  43.        ObjResult.Status = 0;  
  44.        ObjResult.Message = ex.Message;  
  45.        response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);  
  46.    }  
  47.    return response;  
  48. }  
Step 4: Now open the POSTMAN and call the following url:

http://localhost:64016/api/Cricketers/UpdateCricketerInfo


Now change the HttpVerb to PUT and click on send after defining the updating values as per the following screenshot:

Put Call in Web API
                                                   Figure 15: Put Call in Web API

In the above screenshot you can that see that record is successfully updated.

DELETE

In this method we will delete the CricketerInfo from the database. So we will create the method for deleting info and define it as HttpDelete. Add the following code in the Controller:
  1. ///<summary>  
  2. /// This method is used to delete the cricketer info  
  3. ///</summary>  
  4. ///<param name="CricketerId"></param>  
  5. ///<returns></returns>  
  6. [HttpDelete, ActionName("DeleteCricketerInfo")]  
  7. public HttpResponseMessage DeleteCricketerInfo(int CricketerId)  
  8. {  
  9.     Result ObjResult;  
  10.     int result;  
  11.     cricketerBL = newCricketerBL();  
  12.   
  13.     try  
  14.     {  
  15.         CricketerProfile cricketer = newCricketerProfile();  
  16.         cricketer.Id = CricketerId;  
  17.   
  18.         result = cricketerBL.DeleteCricketerInfo(cricketer);  
  19.         if (result > 0)  
  20.         {  
  21.             if (result == 1)  
  22.             {  
  23.                 ObjResult = newResult();  
  24.                 ObjResult.Status = result;  
  25.                 ObjResult.Message = "Record Deleted Successfully!!";  
  26.                 response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);  
  27.             }  
  28.             else if (result == 2)  
  29.             {  
  30.                 ObjResult = newResult();  
  31.                 ObjResult.Status = result;  
  32.                 ObjResult.Message = "Record does not Exists!!";  
  33.                 response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);  
  34.             }  
  35.             else  
  36.             {  
  37.                 ObjResult = newResult();  
  38.                 ObjResult.Status = result;  
  39.                 ObjResult.Message = "Record Not Found!!";  
  40.                 response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);  
  41.             }  
  42.         }  
  43.     }  
  44.     catch (Exception ex)  
  45.     {  
  46.         ObjResult = newResult();  
  47.         ObjResult.Status = 0;  
  48.         ObjResult.Message = ex.Message;  
  49.         response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);  
  50.     }  
  51.     return response;  
  52. }  
Step 5: Now open the POSTMAN and call the following url:

http://localhost:64016/api/Cricketers/DeleteCricketerInfo?CricketerId=6

Now change the HttpVerb to DELETE and click on send as per the following screenshot:

DELETE Call in Web API
                                                Figure 16: DELETE Call in Web API

That’s it. We have successfully created a Web API Controller in which we have used the most commonly used methods (GET, PUT, POST and DELETE).

Summary

So far this article introduces you with the RESTful architecture of Web API and with the help of this article you can get the basic idea of ASP.NET Web API. You can learn the basic objective of creating GET, PUT, POST, DELETE methods and how to call these methods from POSTMAN. In the next article we will play with some advance features of Web API Management. Thanks for reading the article.


Similar Articles