An Overview Of ASP.NET Web API

This demo is created to get the basic understanding of WebAPI. We will be creating a RESTful Web API using Visual Studio 2017.

Before going through this, I assume you have a basic understanding of the following.

  • What is WebAPI
  • .NET Visual studio 2017
  • ASP.NET Core
  • Dapper for SQL queries
  • Postman

The very first step to start the project is to create a table in the SQL database. You can use any databases like MySQL or SQL Express. For demo purposes, I am using SQL Server.

Use the below SQL script to create a table used in this demo.

  1. CREATE TABLE [dbo].[Employee](  
  2.     [EmployeeId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](20) NOT NULL,  
  4.     [City] [varchar](20) ,  
  5.     [Department] [varchar](20),  
  6.     [JoinDate] date  
  7. ON [PRIMARY]  
  8.   
  9. GO  
  10.   
  11. SET ANSI_PADDING OFF  
  12. GO  

Now, open VS 2017 and create a new project, as shown below.

ASP.NET Web API 

Select the API (Project template for RESTFull HTTP service). Please uncheck HTTPS as we are not using it here for demo purposes. Also, you can select Docker support by selecting "Enable Docker support", however, we will install it later using NuGet Package Manager.

ASP.NET Web API 

Click OK and VS will create a project template for you, as shown below.

ASP.NET Web API 

Under Solution Explorer, go to Dependencies and install the following packages required for this project. Please note that we are not using the latest builds for these packages as it is creating compatibility issues in building the WebAPI using VS 2017 template.

ASP.NET Web API
 
ASP.NET Web API 

Once completed, add a folder named "Models" under the Project folder and add a class Emp.cs.

ASP.NET Web API 

Add the following lines of code to the Employee class.

  1. public class Emp  
  2. {  
  3.     public int EmployeeId;  
  4.     public string EmployeeName;  
  5.     public string EmpCity;  
  6.     public string Department;  
  7. }  

Now, we have to add a data layer to get the data from the database. We already installed Dapper in our project. Dapper is having extension methods to fetch and store the data from the database. To read more about the package, please follow the link below.

Also, you can use ADO.NET or any other connection manager if you don’t want to use this method to connect to your database.

Here, we are creating a simple Interface and class to get the data from the database. To do so, add a folder “DataAccess” and add the following two classes to it.

  • IDataProvider.cs : Interface
  • EmpDataAccess.cs: Data Access

ASP.NET Web API

Now, add the following code to the IDataProvider class.
  1. Task<IEnumerable<Emp>> GetAllEmployees();  
  2. Task<Emp> GetEmployee(int empid);    

To provide the features to get all employee and to search employee using employee id, we have to add the following code for EmpDataAccess class.

Make sure to use the following references for EmpDataAccess class.

  1. using Employee.WebAPI.Models;  
  2. using System.Data.SqlClient;  
  3. using System.Data;  
  4. using Dapper;  
  5.   
  6. public class EmpDataAccess: IDataProvider  
  7. {  
  8.     private readonly string connectionString = "your connection";  
  9.     public async Task<Emp> GetEmployee(int Id)  
  10.     {  
  11.         string _sql = "select * from Employee where EmployeeID =1=@eid order by dt_updated desc";  
  12.         using (var sqlConnection = new SqlConnection(connectionString))  
  13.         {  
  14.             await sqlConnection.OpenAsync();  
  15.             var dynamicParameters = new DynamicParameters();  
  16.             dynamicParameters.Add("@eid", Id);  
  17.             return await sqlConnection.QuerySingleOrDefaultAsync<Emp>(  
  18.                 _sql,  
  19.                 dynamicParameters,  
  20.                 commandType: CommandType.Text);  
  21.         }
  22.     }  
  23.     public async Task<IEnumerable<Emp>> GetAllEmployees()  
  24.     {  
  25.         string _sql = "select * from Employee";  
  26.         using (var sqlConnection = new SqlConnection(connectionString))  
  27.         {  
  28.             await sqlConnection.OpenAsync();  
  29.             return await sqlConnection.QueryAsync<Emp>(  
  30.                 _sql,  
  31.                 null,  
  32.                 commandType: CommandType.Text);  
  33.         }
  34.     }  
  35. }  

Add the following code to your interface.

  1. public interface IDataProvider  
  2. {  
  3.     Task<IEnumerable<Emp>> GetAllEmployees();  
  4.     Task<Emp> GetEmployee(int empid);          
  5. }  

Please note that to pass the dynamic parameter using Dapper, we have to set the query variable.

  1. dynamicParameters.Add("@eid", Id);  

Now, the back-end part is almost done and we have to expose these functions over HTTP or HTTPS. To do so, we have to create a controller in our project.

It’s always better to create a controller from the project template. Since we used VS 2017, we already have one default controller; however, we are not using that one (But keep it for reference). We will be adding a new controller that is more meaningful to our project, as EmployeeController.

Adding a controller is easy but you need to understand what type of controller you want to use for your project. Add a Scaffold template from available types or you can add a blank class and use it as a controller.

In this project, we are using empty API Controller. Once you have added a controller using a template, update the controller with the following code.

Here, we are changing the API URL to more meaningful names.

  1. namespace Employee.WebAPI.Controllers  
  2. {  
  3.     //[Route("api/[controller]")]  
  4.     [ApiController]  
  5.     public class EmployeeController : Controller  
  6.     {  
  7.         private IDataProvider empDataProvider;  
  8.   
  9.         public EmployeeController(IDataProvider _empDataProvider)  
  10.         {  
  11.             this.empDataProvider = _empDataProvider;  
  12.         }  
  13.   
  14.         [HttpGet]  
  15.         public async Task<IEnumerable<Emp>> GetAllEmployee()  
  16.         {  
  17.             return await this.empDataProvider.GetAllEmployees();  
  18.         }  
  19.   
  20.         [Route("api/Employee/GetEmp")]          
  21.         [HttpGet]  
  22.         public async Task<Emp> GetEmp(int empid)  
  23.         {  
  24.             return await this.empDataProvider.GetEmployee(empid);  
  25.         }  
  26.   
  27.     }  
  28. }  

Now, try to build and run the project. You might get into the following issues while trying to call the Employee service using POSTMAN.

ASP.NET Web API 

Open the StartUp.cs class and register the implementation type for the new controller service.

  1. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  2. services.AddTransient<IDataProvider, EmpDataAccess>();  

Once done, run the application and test the Web API using POSTMAN.

Below are the two URL to test the application.

To get all employees, run "api/Employee/GetEmp" as defined in the controller route.

ASP.NET Web API 

To fetch an employee based on the Employee number.

ASP.NET Web API 

You can observe that you are able to get the data from the Web API, however, EmployeeName and EmpCity are showing as NULL even if you have good value in the database. This is because our model Emp class in not bound with the database table and there is no mapping defined as well.

  1. {  
  2.     "employeeId": 1,  
  3.     "employeeName"null,  
  4.     "empCity"null,  
  5.     "department""IT"  
  6. }  

We will sort out these issue in later reads. If you want to fix the problem, simply change the Model Emp class as below.

  1. public class Emp  
  2. {  
  3.     //public int EmployeeId;  
  4.     //public string EmployeeName;  
  5.     //public string EmpCity;  
  6.     //public string Department;  
  7.     public int EmployeeId;  
  8.     public string Name;  
  9.     public string City;  
  10.     public string Department;  
  11. }  

Here is the JSON result after updating the Emp classs.

  1. {  
  2.     "employeeId": 1,  
  3.     "name""John",  
  4.     "city""New York",  
  5.     "department""IT"  
  6. }  


Similar Articles