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.
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:
- [HttpGet, ActionName("GetInfo")]
- public HttpResponseMessage GetInfo()
- {
-
- }
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
- [HttpPost, ActionName("PostInfo")]
- public HttpResponseMessage PostInfo(Result result)
- {
-
- }
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
- [HttpPut, ActionName("UpdateInfo")]
- public HttpResponseMessage UpdateInfo(Result result)
- {
-
- }
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
- [HttpDelete, ActionName("DeleteInfo")]
- public HttpResponseMessage DeleteInfo(int UserId)
- {
-
- }
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”.
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.
Figure 2: Creating New Application
Step 3: In the next ASP.NET wizard select the
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:
- USE[Cricketer]
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerList] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerList]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_GetCricketerList]
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerDetailsById] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerDetailsById]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_GetCricketerDetailsById]
- GO
- /****** Object: StoredProcedure [dbo].[CC_DeleteCricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_DeleteCricketerProfile]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_DeleteCricketerProfile]
- GO
- /****** Object: StoredProcedure [dbo].[CC_AddUpdateCricketerDetails] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_AddUpdateCricketerDetails]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_AddUpdateCricketerDetails]
- GO
- /****** Object: Table [dbo].[CricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CricketerProfile]') ANDtypein(N 'U'))
- DROP TABLE[dbo].[CricketerProfile]
- GO
- /****** Object: Table [dbo].[CricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/
- SET ANSI_NULLSON
- GO
- SET QUOTED_IDENTIFIERON
- GO
- SETANSI_PADDINGON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CricketerProfile]') ANDtypein(N 'U'))
- BEGIN
- CREATE TABLE[dbo].[CricketerProfile](
- [ID][int] IDENTITY(1, 1) NOTNULL, [Name][varchar](50) NULL, [ODI][int] NULL, [Tests][int] NULL, [ODIRuns][int] NULL, [TestRuns][int] NULL,
- CONSTRAINT[PK_CricketerProfile] PRIMARYKEYCLUSTERED(
- [ID] ASC
- ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]
- ) ON[PRIMARY]
- END
- GO
- SETANSI_PADDINGOFF
- GO
- SETIDENTITY_INSERT[dbo].[CricketerProfile] ON
-
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(1, N 'Sachin Tendulkar', 463, 200, 18426, 15921)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(2, N 'Saurav Ganguly', 311, 113, 11363, 7212)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(3, N 'Rahul Dravid', 344, 164, 10889, 13228)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(4, N 'V.V.S. Laxman', 86, 134, 2338, 8781)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(5, N 'Virendar Sehwag', 251, 104, 8273, 8586)
- GO
- SETIDENTITY_INSERT[dbo].[CricketerProfile] OFF
- GO
- /****** Object: StoredProcedure [dbo].[CC_AddUpdateCricketerDetails] Script Date: 1/31/2016 8:50:45 PM ******/
- SETANSI_NULLSON
- GO
- SETQUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_AddUpdateCricketerDetails]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_AddUpdateCricketerDetails] AS'
- END
- GO
-
-
-
-
-
- ALTERPROCEDURE CC_AddUpdateCricketerDetails
-
- for the stored procedure here
- @Id INT = NULL,
- @Name VARCHAR(50),
- @ODI INT = NULL,
- @Tests INT = NULL,
- @OdiRuns INT = NULL,
- @TestRuns INT = NULL,
- @Type INT,
- for Add Record and 2
- for Update Record
- @Status INTOUT
- AS
- BEGIN
-
-
-
- IF(@Type = 1)
- BEGIN
- IFNOTEXISTS(SELECT cp.Name FROM dbo.CricketerProfile(NOLOCK) cp WHERE cp.Name LIKE '%' + @Name + '%')
- BEGIN
- INSERT INTO dbo.CricketerProfile
- (
- Name,
- ODI,
- Tests,
- ODIRuns,
- TestRuns
- )
- VALUES(@Name,
- IF(@ @ROWCOUNT > 0)
- BEGIN
- SET @Status = 1;
-
- END;
- END;
- ELSE
- BEGIN
- SET @Status = 2;
-
- END;
- END;
- ELSE
- IF(@Type = 2)
- BEGIN
- IFEXISTS(SELECT ccp.ID FROM dbo.CricketerProfile ccp(NOLOCK) WHERE ccp.ID = @Id)
- BEGIN
- UPDATE dbo.CricketerProfile
- SET Name = ISNULL(@Name, Name),
- ODI = ISNULL(@ODI, ODI),
- Tests = ISNULL(@Tests, Tests),
- ODIRuns = ISNULL(@OdiRuns, ODIRuns),
- TestRuns = ISNULL(@TestRuns, TestRuns)
- WHERE ID = @Id;
- IF(@ @ROWCOUNT > 0)
- BEGIN
- SET @Status = 3;
-
- END;
- END;
- ELSE
- BEGIN
- SET @Status = 4;
-
- END;
- END;
- END;
- GO
- /****** Object: StoredProcedure [dbo].[CC_DeleteCricketerProfile] Script Date: 1/31/2016 8:50:45 PM ******/
- SETANSI_NULLSON
- GO
- SETQUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_DeleteCricketerProfile]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_DeleteCricketerProfile] AS'
- END
- GO
-
-
-
-
-
- ALTERPROCEDURE[dbo].[CC_DeleteCricketerProfile]
-
- for the stored procedure here
- @Id INT, @Status INTOUT
- AS
- BEGIN
-
-
- IFEXISTS(SELECT cp.ID FROM dbo.CricketerProfile cp(NOLOCK) WHERE cp.ID = @Id)
- BEGIN
- DELETE FROM dbo.CricketerProfile
- WHERE ID = @Id;
- IF(@ @ROWCOUNT > 0)
- BEGIN
- SET @Status = 1;
-
- END;
- END;
- ELSE
- BEGIN
- SET @Status = 2;
-
- END;
- END;
-
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerDetailsById] Script Date: 1/31/2016 8:50:45 PM ******/
- SET ANSI_NULLSON
- GO
- SET QUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerDetailsById]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_GetCricketerDetailsById] AS'
- END
- GO
- ALTER Proc[dbo].[CC_GetCricketerDetailsById]
- @ID int
- AS
- Begin
- select * from CricketerProfile(NOLOCK) where ID = @Id
- End
-
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerList] Script Date: 1/31/2016 8:50:45 PM ******/
- SET ANSI_NULLSON
- GO
- SET QUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerList]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_GetCricketerList] AS'
- END
- GO
- ALTERVProc[dbo].[CC_GetCricketerList]
- AS
- Begin
- select ID, Name from CricketerProfile(NOLOCK)
- End
- 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”
Figure 4: Adding New Solution Folder
Step 2: Add a “
New Project” in the
Models folder
Figure 5: Adding New Project
Step 3: Select
Class Library template to add a new project and name it “
BestCricketers.Models”.
Figure 6: Adding Class Library
Step 4: Add a new class named “CricketerProfile” and replace the code with the following code:
- public class CricketerProfile: Result
- {
- public int Id
- {
- get;
- set;
- }
- public string Name
- {
- get;
- set;
- }
- public int ODI
- {
- get;
- set;
- }
- public int Tests
- {
- get;
- set;
- }
- public int OdiRuns
- {
- get;
- set;
- }
- public int TestRuns
- {
- get;
- set;
- }
- public int Type
- {
- get;
- set;
- }
- }
-
- public class Result
- {
- public int Status
- {
- get;
- set;
- }
- public string Message
- {
- get;
- set;
- }
- }
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,
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:
- namespace BestCricketers.Core.DAL {
- publicclassCricketerDAL {
- #region Variable
-
-
-
- Database objDB;
-
-
-
- staticstring ConnectionString;#
- endregion# region Constructor
-
-
-
- public CricketerDAL() {
- ConnectionString = ConfigurationManager.ConnectionStrings["CricketerConnectionString"].ToString();
- }
- #endregion
- #region Database Method
- publicList < T > ConvertTo < T > (DataTable datatable) whereT: new() {
- List < T > Temp = newList < T > ();
- try {
- List < string > columnsNames = newList < string > ();
- foreach(DataColumn DataColumn in datatable.Columns)
- columnsNames.Add(DataColumn.ColumnName);
- Temp = datatable.AsEnumerable().ToList().ConvertAll < T > (row => getObject < T > (row, columnsNames));
- return Temp;
- }
- catch {
- return Temp;
- }
- }
- publicT getObject < T > (DataRow row, List < string > columnsName) whereT: new() {
- T obj = newT();
- try {
- string columnname = "";
- string value = "";
- PropertyInfo[] Properties;
- Properties = typeof (T).GetProperties();
- foreach(PropertyInfo objProperty in Properties) {
- columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
- if (!string.IsNullOrEmpty(columnname)) {
- value = row[columnname].ToString();
- if (!string.IsNullOrEmpty(value)) {
- if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) {
- value = row[columnname].ToString().Replace("$", "").Replace(",", "");
- objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
- } else {
- value = row[columnname].ToString();
- objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
- }
- }
- }
- }
- return obj;
- }
- catch (Exception ex) {
- return obj;
- }
- }
- #endregion
- #region CricketerProfile
-
-
-
-
- publicList < CricketerProfile > GetCricketerList() {
- List < CricketerProfile > objGetCricketers = null;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerList")) {
- try {
- using(DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0]) {
- objGetCricketers = ConvertTo < CricketerProfile > (dataTable);
- }
- }
- catch (Exception ex) {
- throw ex;
- returnnull;
- }
- }
- return objGetCricketers;
- }
-
-
-
-
- publicList < CricketerProfile > GetCricketerDetailsById(int Id) {
- List < CricketerProfile > objCricketerDetails = null;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerDetailsById")) {
- try {
- objDB.AddInParameter(objcmd, "@ID", DbType.Int32, Id);
- using(DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0]) {
- objCricketerDetails = ConvertTo < CricketerProfile > (dataTable);
- }
- }
- catch (Exception ex) {
- throw ex;
- returnnull;
- }
- }
- return objCricketerDetails;
- }
-
-
-
-
-
- publicint AddUpdateCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objCMD = objDB.GetStoredProcCommand("CC_AddUpdateCricketerDetails")) {
- objDB.AddInParameter(objCMD, "@Id", DbType.Int32, cricketer.Id);
- if (string.IsNullOrEmpty(cricketer.Name)) objDB.AddInParameter(objCMD, "@Name", DbType.String, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@Name", DbType.String, cricketer.Name);
- if (cricketer.ODI == 0) objDB.AddInParameter(objCMD, "@ODI", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@ODI", DbType.Int32, cricketer.ODI);
- if (cricketer.Tests == 0) objDB.AddInParameter(objCMD, "@Tests", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@Tests", DbType.Int32, cricketer.Tests);
- if (cricketer.OdiRuns == 0) objDB.AddInParameter(objCMD, "@OdiRuns", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@OdiRuns", DbType.Int32, cricketer.OdiRuns);
- if (cricketer.TestRuns == 0) objDB.AddInParameter(objCMD, "@TestRuns", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@TestRuns", DbType.Int32, cricketer.TestRuns);
- objDB.AddInParameter(objCMD, "@Type", DbType.Int32, cricketer.Type);
- objDB.AddOutParameter(objCMD, "@Status", DbType.Int16, 0);
- try {
- objDB.ExecuteNonQuery(objCMD);
- result = Convert.ToInt32(objDB.GetParameterValue(objCMD, "@Status"));
- }
- catch (Exception) {
- throw;
- }
- }
- return result;
- }
-
-
-
-
-
- publicint DeleteCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objCMD = objDB.GetStoredProcCommand("CC_DeleteCricketerProfile")) {
- objDB.AddInParameter(objCMD, "@Id", DbType.Int32, cricketer.Id);
- objDB.AddOutParameter(objCMD, "@Status", DbType.Int16, 0);
- try {
- objDB.ExecuteNonQuery(objCMD);
- result = Convert.ToInt32(objDB.GetParameterValue(objCMD, "@Status"));
- }
- catch (Exception) {
- throw;
- }
- }
- return result;
- }
- #endregion
- }
- }
Step 8: Add a new class “CricketerBL” in the BL folder and replace the code with the following code:
- namespace BestCricketers.Core.BL {
- publicclassCricketerBL {
-
-
-
-
- publicList < CricketerProfile > GetCricketerList() {
- List < CricketerProfile > ObjCricketers = null;
- try {
- ObjCricketers = newCricketerDAL().GetCricketerList();
- }
- catch (Exception) {
- throw;
- }
- return ObjCricketers;
- }
-
-
-
-
- publicList < CricketerProfile > GetCricketerDetailsById(int Id) {
- List < CricketerProfile > ObjCricketerDetails = null;
- try {
- ObjCricketerDetails = newCricketerDAL().GetCricketerDetailsById(Id);
- }
- catch (Exception) {
- throw;
- }
- return ObjCricketerDetails;
- }
-
-
-
-
-
- publicint AddUpdateCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- try {
- result = newCricketerDAL().AddUpdateCricketerInfo(cricketer);
- }
- catch (Exception) {
- return 0;
- }
- return result;
- }
-
-
-
-
-
- publicint DeleteCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- try {
- result = newCricketerDAL().DeleteCricketerInfo(cricketer);
- } catch (Exception) {
- return 0;
- }
- return result;
- }
- }
- }
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,
Figure 8: Adding New Controller
Step 2: Select the “
Web API 2 Controller - Empty” in the next wizard
Figure 9: Add Scaffold Wizard
Step 3: Now enter the controller name as “
CricketersController”
Figure 10: Adding Controller
Step 4: Add the following connection string in the “<ConnectionStrings>” tab in your “Web.config” file of the API project:
- <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:
- using BestCricketers.Core.BL;
- using BestCricketers.Models;
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace BestCricketers.Controllers {
- publicclassCricketersController: ApiController {
- #region Variable
- HttpResponseMessage response;
- CricketerBL cricketerBL;
- #endregion# region Public Method
-
-
-
-
- [HttpGet, ActionName("GetCricketerList")]
- publicHttpResponseMessage GetCricketerList() {
- Result result;
- cricketerBL = newCricketerBL();
- try {
- var cricketerList = cricketerBL.GetCricketerList();
- if (!object.Equals(cricketerList, null)) {
- response = Request.CreateResponse < List < CricketerProfile >> (HttpStatusCode.OK, cricketerList);
- }
- }
- catch (Exception ex) {
- result = newResult();
- result.Status = 0;
- result.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, result);
- }
- return response;
- }
-
-
-
-
- [HttpGet, ActionName("GetCricketerInfoById")]
- publicHttpResponseMessage GetCricketerInfoById(int CricketerId) {
- Result result;
- cricketerBL = newCricketerBL();
- try {
- var cricketerList = cricketerBL.GetCricketerDetailsById(CricketerId);
- if (!object.Equals(cricketerList, null)) {
- response = Request.CreateResponse < List < CricketerProfile >> (HttpStatusCode.OK, cricketerList);
- }
- }
- catch (Exception ex) {
- result = newResult();
- result.Status = 0;
- result.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, result);
- }
- return response;
- }#endregion
- }
- }
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,
Figure 11: Simple GET Call
Get Call with Parameter
Call Url: http://localhost:64016/api/Cricketers/GetCricketerInfoById?Cricketerid=1 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:
-
-
-
-
- [HttpPost, ActionName("AddCricketerInfo")]
- publicHttpResponseMessage AddCricketerInfo(CricketerProfile Cricketer) {
- Result ObjResult;
- int result;
- cricketerBL = newCricketerBL();
- try {
- result = cricketerBL.AddUpdateCricketerInfo(Cricketer);
- if (result > 0) {
- if (result == 1) {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Inserted Successfully!!";
- response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);
- }
- elseif(result == 2) {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Already Exists!!";
- response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);
- }
- else {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Not Added!!";
- response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);
- }
- }
- }
- catch (Exception ex) {
- ObjResult = newResult();
- ObjResult.Status = 0;
- ObjResult.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);
- }
- return response;
- }
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:
Figure 13: Headers in POST Call
Now click on
Send,
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:
-
-
-
-
-
- [HttpPut, ActionName("UpdateCricketerInfo")]
- publicHttpResponseMessage UpdateCricketerInfo(CricketerProfile Cricketer)
- {
- Result ObjResult;
- int result;
- cricketerBL = newCricketerBL();
- try {
- result = cricketerBL.AddUpdateCricketerInfo(Cricketer);
-
- if (result > 0)
- {
- if (result == 3)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Updated Successfully!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- elseif (result == 2)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record does not Exists!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- else
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Not Added!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- }
- }
- catch (Exception ex)
- {
- ObjResult = newResult();
- ObjResult.Status = 0;
- ObjResult.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);
- }
- return response;
- }
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:
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:
-
-
-
-
-
- [HttpDelete, ActionName("DeleteCricketerInfo")]
- publicHttpResponseMessage DeleteCricketerInfo(int CricketerId)
- {
- Result ObjResult;
- int result;
- cricketerBL = newCricketerBL();
-
- try
- {
- CricketerProfile cricketer = newCricketerProfile();
- cricketer.Id = CricketerId;
-
- result = cricketerBL.DeleteCricketerInfo(cricketer);
- if (result > 0)
- {
- if (result == 1)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Deleted Successfully!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- elseif (result == 2)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record does not Exists!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- else
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Not Found!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- }
- }
- catch (Exception ex)
- {
- ObjResult = newResult();
- ObjResult.Status = 0;
- ObjResult.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);
- }
- return response;
- }
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:
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.