Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application

Introduction

 
In this step by step tutorial, I'm going to perform login and CRUD operations in ASP.NET Web API using an Angular 9 Web application. The backend is a Microsoft SQL Server database. A Web API is used to provide data connectivity between the database and the front end application. On the UI side, I will use the Angular Material to create a rich, interactive, and device-independent user experience.
 
In this article, we will learn the step-by-step process of creating login and CRUD operations in ASP.NET Web API using Angular 9 with the following technologies:
  1. ASP.NET Web API.
  2. Angular 9.
  3. Microsoft SQL Server
  4. Angular Material
  5. Bootstrap
Download Requirements
  1. Basic knowledge of Angular and Web API.
  2. Visual Studio Code and Visual Studio should be installed.
  3. MS SQL Server and SQL Server Management Studio should be installed.
  4. Nodejs should be installed.
Step 1
 
Open SQL Server Management Studio, create a database named Employee, and in this database, create a three table. Give that table a name like Employeemaster, Employees, and Departments.
 
Open a new query and run this code in the query section:
 
Create a Database named Employee.
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Create a table Employeemaster using a query or design any of these:
  1. CREATE TABLE [dbo].[Employeemaster](  
  2. [UserId] [int] IDENTITY(1,1) NOT NULL,  
  3. [UserName] [varchar](50) NOT NULL,  
  4. [LoginName] [varchar](50) NULL,  
  5. [Password] [varchar](50) NOT NULL,  
  6. [Email] [varchar](50) NULL,  
  7. [ContactNo] [varchar](15) NULL,  
  8. [Address] [varchar](50) NULL,  
  9. [IsApporved] [intNULL,  
  10. [Status] [intNULL,  
  11. [TotalCnt] [intNULL,  
  12. PRIMARY KEY CLUSTERED  
  13. (  
  14.    [UserId] ASC  
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16. ON [PRIMARY]  
  17. GO  
OR
 
Create a design table in the database:
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Now, for Login purposes, create a stored procedure with the name Usp_Login for adding a login functionality:
  1. create proc [dbo].[Usp_Login]  
  2. @UserName varchar(50)='',  
  3. @Password varchar(50)=''  
  4. as begin  
  5. declare @UserId int =0,@TotalCnt int =0  
  6. select @UserId=UserId,@TotalCnt=TotalCnt from Employeemaster um  
  7. where LoginName=@UserName and Password=@Password and Status<>3 and IsApporved=1  
  8. if(@TotalCnt>=5)  
  9. begin  
  10. select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,  
  11. ''Address,0 IsApporved,-1 Status  
  12. end  
  13. if(@UserId>0)  
  14. begin  
  15. select UserId, UserName, LoginName, Password, Email, ContactNo,  
  16. Address, IsApporved, Status from Employeemaster um  
  17. where UserId=@UserId  
  18. --update Employeemaster set Status=2 where UserId=@UserId  
  19. end  
  20. else  
  21. begin  
  22. Update Employeemaster set @TotalCnt=TotalCnt+1  
  23. where LoginName=@UserName and Status=1 and IsApporved=1  
  24. select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,  
  25. ''Address,0 IsApporved,0 Status  
  26. end end  
Create a table, Employee:
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Create a table, Department:
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Step 2
 
Open Visual Studio >> File >> New >> Project >> Select Web Application. After that, click OK and you will see the templates. Select the Web API template and click OK. You will see something like this:
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Step 3
 
Now, Select Models folder >> Right click >>Add >> New Item >> select Data in left panel >>ADO.NET Entity Data Model,
 
Click on the ADO.NET Entity Data Model option and click Add.
 
Select EF designer from the database and click the Next button.
 
Add the connection properties, select database name on the next page, and click OK.
 
Check the Tables and Stored procedure checkboxes.
 
The internal options will be selected by default. Now, click the Finish button.
 
Our data model is now created like this:
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
Step 4
 
Again, Right-click on the Models folder and add two classes — Login and Response respectively.
 
Response.cs:
  1. public class Response {  
  2.     public string Status {  
  3.         set;  
  4.         get;  
  5.     }  
  6.     public string Message {  
  7.         set;  
  8.         get;  
  9.     }  
  10. }  
Login.cs
  1. public class Login {  
  2.     public string UserName {  
  3.         set;  
  4.         get;  
  5.     }  
  6.     public string Password {  
  7.         set;  
  8.         get;  
  9.     }  
  10. }  
  11. public class Registration: Employeemaster {}  
Now, paste the following codes in these classes:
  1. using LoginAPI.Models;  
Step 5
 
Go to the Controller folder in our API Application and right-click >> Add >> Controller >> Select Web API 2 Controller-Empty and then add a new controller. Name it as Logincontroller, DepartmentController,EmployeeController.
 
Now, we will go to the Login controller with the following lines of code:
  1. using LoginAPI.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. namespace LoginAPI.Controllers {  
  9.     public class LoginController: ApiController {  
  10.         //For user login  
  11.         [Route("Api/Login/UserLogin")]  
  12.         [HttpPost]  
  13.         public Response Login(Login Lg) {  
  14.             EmployeeEntities DB = new EmployeeEntities();  
  15.             var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList < Usp_Login_Result > ().FirstOrDefault();  
  16.             if (Obj.Status == 0) return new Response {  
  17.                 Status = "Invalid", Message = "Invalid User."  
  18.             };  
  19.             if (Obj.Status == -1) return new Response {  
  20.                 Status = "Inactive", Message = "User Inactive."  
  21.             };  
  22.             else return new Response {  
  23.                 Status = "Success", Message = Lg.UserName  
  24.             };  
  25.         }  
  26.         //For new user Registration  
  27.         [Route("Api/Login/UserRegistration")]  
  28.         [HttpPost]  
  29.         public object createcontact(Registration Lvm) {  
  30.             try {  
  31.                 EmployeeEntities1 db = new EmployeeEntities1();  
  32.                 Employeemaster Em = new Employeemaster();  
  33.                 if (Em.UserId == 0) {  
  34.                     Em.UserName = Lvm.UserName;  
  35.                     Em.LoginName = Lvm.LoginName;  
  36.                     Em.Password = Lvm.Password;  
  37.                     Em.Email = Lvm.Email;  
  38.                     Em.ContactNo = Lvm.ContactNo;  
  39.                     Em.Address = Lvm.Address;  
  40.                     Em.IsApporved = Lvm.IsApporved;  
  41.                     Em.Status = Lvm.Status;  
  42.                     db.Employeemasters.Add(Em);  
  43.                     db.SaveChanges();  
  44.                     return new Response {  
  45.                         Status = "Success", Message = "SuccessFully Saved."  
  46.                     };  
  47.                 }  
  48.             } catch (Exception) {  
  49.                 throw;  
  50.             }  
  51.             return new Response {  
  52.                 Status = "Error", Message = "Invalid Data."  
  53.             };  
  54.         }  
  55.     }  
  56. }  
Now, we will go to the Department controller with the following lines of code:
  1. using LoginAPI.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Configuration;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Linq;  
  8. using System.Net;  
  9. using System.Net.Http;  
  10. using System.Web.Http;  
  11. namespace LoginAPI.Controllers {  
  12.     [RoutePrefix("Api/Department")]  
  13.     public class DepartmentController: ApiController {  
  14.         private EmployeeEntities objEntity = new EmployeeEntities();  
  15.         [HttpGet]  
  16.         [Route("AllDepartments")]  
  17.         public IQueryable < Department > GetDepartment() {  
  18.                 try {  
  19.                     return objEntity.Departments;  
  20.                 } catch (Exception) {  
  21.                     throw;  
  22.                 }  
  23.             }  
  24.             [HttpGet]  
  25.             [Route("GetDepartmentsById/{DepartmentID}")]  
  26.         public IHttpActionResult GetDepartmentById(string DepartmentID) {  
  27.                 Department objDep = new Department();  
  28.                 int ID = Convert.ToInt32(DepartmentID);  
  29.                 try {  
  30.                     objDep = objEntity.Departments.Find(ID);  
  31.                     if (objDep == null) {  
  32.                         return NotFound();  
  33.                     }  
  34.                 } catch (Exception) {  
  35.                     throw;  
  36.                 }  
  37.                 return Ok(objDep);  
  38.             }  
  39.             [HttpPost]  
  40.             [Route("InsertDepartments")]  
  41.         public IHttpActionResult PostDepartment(Department data) {  
  42.                 if (!ModelState.IsValid) {  
  43.                     return BadRequest(ModelState);  
  44.                 }  
  45.                 try {  
  46.                     objEntity.Departments.Add(data);  
  47.                     objEntity.SaveChanges();  
  48.                 } catch (Exception) {  
  49.                     throw;  
  50.                 }  
  51.                 return Ok(data);  
  52.             }  
  53.             [HttpPut]  
  54.             [Route("UpdateDepartments")]  
  55.         public IHttpActionResult PutDepartment(Department department) {  
  56.                 if (!ModelState.IsValid) {  
  57.                     return BadRequest(ModelState);  
  58.                 }  
  59.                 try {  
  60.                     Department objDep = new Department();  
  61.                     objDep = objEntity.Departments.Find(department.DepartmentID);  
  62.                     if (objDep != null) {  
  63.                         objDep.DepartmentName = department.DepartmentName;  
  64.                     }  
  65.                     int i = this.objEntity.SaveChanges();  
  66.                 } catch (Exception) {  
  67.                     throw;  
  68.                 }  
  69.                 return Ok(department);  
  70.             }  
  71.             [HttpDelete]  
  72.             [Route("DeleteDepartments")]  
  73.         public IHttpActionResult DeleteDepartment(int id) {  
  74.             //int empId = Convert.ToInt32(id);  
  75.             Department department = objEntity.Departments.Find(id);  
  76.             if (department == null) {  
  77.                 return NotFound();  
  78.             }  
  79.             objEntity.Departments.Remove(department);  
  80.             objEntity.SaveChanges();  
  81.             return Ok(department);  
  82.         }  
  83.     }  
  84. }  
Now, we will go to the Employee controller with the following lines of code:
  1. using LoginAPI.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. namespace LoginAPI.Controllers {  
  9.     [RoutePrefix("Api/Employee")]  
  10.     public class EmployeeController: ApiController {  
  11.         private EmployeeEntities objEntity = new EmployeeEntities();  
  12.         [HttpGet]  
  13.         [Route("AllEmployees")]  
  14.         public IQueryable < Employee > GetEmployee() {  
  15.                 try {  
  16.                     return objEntity.Employees;  
  17.                 } catch (Exception) {  
  18.                     throw;  
  19.                 }  
  20.             }  
  21.             [HttpGet]  
  22.             [Route("Department")]  
  23.         public IQueryable < Department > GetDepartment() {  
  24.                 try {  
  25.                     return objEntity.Departments;  
  26.                 } catch (Exception) {  
  27.                     throw;  
  28.                 }  
  29.             }  
  30.             [HttpGet]  
  31.             [Route("GetEmployeesById/{employeeId}")]  
  32.         public IHttpActionResult GetEmployeeById(string employeeId) {  
  33.                 Employee objEmp = new Employee();  
  34.                 int ID = Convert.ToInt32(employeeId);  
  35.                 try {  
  36.                     objEmp = objEntity.Employees.Find(ID);  
  37.                     if (objEmp == null) {  
  38.                         return NotFound();  
  39.                     }  
  40.                 } catch (Exception) {  
  41.                     throw;  
  42.                 }  
  43.                 return Ok(objEmp);  
  44.             }  
  45.             [HttpPost]  
  46.             [Route("InsertEmployees")]  
  47.         public IHttpActionResult PostEmployee(Employee data) {  
  48.                 if (!ModelState.IsValid) {  
  49.                     return BadRequest(ModelState);  
  50.                 }  
  51.                 try {  
  52.                     objEntity.Employees.Add(data);  
  53.                     objEntity.SaveChanges();  
  54.                 } catch (Exception) {  
  55.                     throw;  
  56.                 }  
  57.                 return Ok(data);  
  58.             }  
  59.             [HttpPut]  
  60.             [Route("UpdateEmployees")]  
  61.         public IHttpActionResult PutEmployee(Employee employee) {  
  62.                 if (!ModelState.IsValid) {  
  63.                     return BadRequest(ModelState);  
  64.                 }  
  65.                 try {  
  66.                     Employee objEmp = new Employee();  
  67.                     objEmp = objEntity.Employees.Find(employee.EmployeeID);  
  68.                     if (objEmp != null) {  
  69.                         objEmp.EmployeeName = employee.EmployeeName;  
  70.                         objEmp.Department = employee.Department;  
  71.                         objEmp.MailID = employee.MailID;  
  72.                         objEmp.DOJ = employee.DOJ;  
  73.                         objEmp.Address = employee.Address;  
  74.                         objEmp.Phone = employee.Phone;  
  75.                         objEmp.Salary = employee.Salary;  
  76.                         objEmp.Age = employee.Age;  
  77.                     }  
  78.                     int i = this.objEntity.SaveChanges();  
  79.                 } catch (Exception) {  
  80.                     throw;  
  81.                 }  
  82.                 return Ok(employee);  
  83.             }  
  84.             [HttpDelete]  
  85.             [Route("DeleteEmployees")]  
  86.         public IHttpActionResult DeleteEmployee(int id) {  
  87.             //int empId = Convert.ToInt32(id);  
  88.             Employee employee = objEntity.Employees.Find(id);  
  89.             if (employee == null) {  
  90.                 return NotFound();  
  91.             }  
  92.             objEntity.Employees.Remove(employee);  
  93.             objEntity.SaveChanges();  
  94.             return Ok(employee);  
  95.         }  
  96.     }  
  97. }  
Step 6
 
If you consume the Web API, Angular blocks the URL. We call this issue CORS (Cross Origin Resource Sharing).
 
First, let's resolve this problem.
 
Go to the Web API project.
 
Download a Nuget package for CORS. Go to NuGet Package Manager and download the following file.
 
After that, go to the App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
 
Add namespace:
  1. using System.Web.Http.Cors;  
  2. // for JSON data into test data in POSTMAN  
  3. config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
  4. // enable cors helps to connect with angular using http request  
  5. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");  
  6. config.EnableCors(cors);  
Step 7
 
Build a UI Application using Angular 9 Angular CLI and Angular material that will consume the Web API.
 
Now, open Visual Studio Code and create a project to add bootstrap to this project,
 
Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. Using the command:
  1. ng new login // create your login project  
  2. cd login // location to login project  
  3. ng add @angular / material // add angular material  
  4. npm install bootstrap– save // add bootstrap  
  5. ng serve– open // opens your project at localhost://4200  
Now, write the following command that will create components, services, and models.
 
ng g c dashboard
ng g c login 
ng g c register
ng g c employee
ng g c employee/add-emp 
ng g c employee/edit-emp
ng g c employee/show-emp
ng g c employee/delete-emp
ng g c department
ng g c department /add-dep
ng g c department /edit-dep
ng g c department /show-dep
ng g c department /delete-dep 
ng g s login
ng g s department
ng g s employee
ng g class register
ng g class department
ng g class employee
 
Once created, the project should look like this.
 
We have completed all needed code functionality for our Login and CRUD operations using ASP.NET Web API. Before running the application, first, make sure to save your hard work.
 
Now, let's run the app and see how it works.
 
Open TERMINAL and write the following command to run the program.
 
ng serve -open
 
The output looks like the following image. It's a stunning UI created with CRUD operations.
 
Congratulations!
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
 
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
Login And CRUD operations In ASP.NET Web API Using Angular 9 Web Application
You've finished a complete Login and ASP.NET Web API with CRUD functionality. The App uses a Web API to provide data access from an MS SQL Server.
 
All the angular 9 code is zipped above. If you find any problem, please contact me immediately.
 
Thank you for reading this article.
 

Summary

 
In this article, we have discussed the process of Login and CRUD operations in ASP.NET Web API using an Angular 9 Web application.
 
Reference
 
https://github.com/Ukmandal/Employee-Management-Portial
https://dzone.com/articles/login-and-registration-aspnet-web-api-using-angula


Similar Articles