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 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 three tables. 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.

Employee

Create a table Employee master using a query or design any of these.

CREATE TABLE [dbo].[Employeemaster](
    [UserId] [int] IDENTITY(1,1) NOT NULL,
      NOT NULL,
      NULL,
      NOT NULL,
      NULL,
      NULL,
      NULL,
    [IsApporved] [int] NULL,
    [Status] [int] NULL,
    [TotalCnt] [int] NULL,
    PRIMARY KEY CLUSTERED
    (
        [UserId] ASC
    ) WITH (
        PAD_INDEX = OFF, 
        STATISTICS_NORECOMPUTE = OFF, 
        IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, 
        ALLOW_PAGE_LOCKS = ON
    ) ON [PRIMARY]
) ON [PRIMARY]
GO

OR

Create a design table in the database:

Create design

Now, for Login purposes, create a stored procedure with the name Usp_Login for adding a login functionality.

CREATE PROC [dbo].[Usp_Login]
    @UserName VARCHAR(50) = '',
    @Password VARCHAR(50) = ''
AS
BEGIN
    DECLARE @UserId INT = 0, @TotalCnt INT = 0;
    SELECT @UserId = UserId, @TotalCnt = TotalCnt
    FROM Employeemaster um
    WHERE LoginName = @UserName AND Password = @Password AND Status <> 3 AND IsApporved = 1;
    IF (@TotalCnt >= 5)
    BEGIN
        SELECT 0 AS UserId, '' AS UserName, '' AS LoginName, '' AS Password, '' AS Email, '' AS ContactNo, '' AS Address, 0 AS IsApporved, -1 AS Status;
    END
    IF (@UserId > 0)
    BEGIN
        SELECT UserId, UserName, LoginName, Password, Email, ContactNo, Address, IsApporved, Status
        FROM Employeemaster um
        WHERE UserId = @UserId;
        -- UPDATE Employeemaster SET Status = 2 WHERE UserId = @UserId;
    END
    ELSE
    BEGIN
        UPDATE Employeemaster
        SET @TotalCnt = TotalCnt + 1
        WHERE LoginName = @UserName AND Status = 1 AND IsApporved = 1;
        SELECT 0 AS UserId, '' AS UserName, '' AS LoginName, '' AS Password, '' AS Email, '' AS ContactNo, '' AS Address, 0 AS IsApporved, 0 AS Status;
    END
END

Create a table, Employee

Create table

Create a table, Department

Create department

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:

LoginAPI

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 the 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

 

Department

Step 4. Again, Right-click on the Models folder and add two classes — Login and Response respectively.

Response.cs

public class Response
{
    public string Status { get; set; }
    public string Message { get; set; }
}

Login.cs

public class Login
{
    public string UserName { get; set; }
    public string Password { get; set; }
}
public class Registration : Employeemaster
{
}

Now, paste the following codes into these classes.

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, or EmployeeController.

Now, we will go to the Login controller with the following lines of code.

using LoginAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace LoginAPI.Controllers
{
    public class LoginController : ApiController
    {
        // For user login
        [Route("Api/Login/UserLogin")]
        [HttpPost]
        public Response Login(Login Lg)
        {
            EmployeeEntities DB = new EmployeeEntities();
            var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList<Usp_Login_Result>().FirstOrDefault();
            if (Obj.Status == 0)
                return new Response { Status = "Invalid", Message = "Invalid User." };
            if (Obj.Status == -1)
                return new Response { Status = "Inactive", Message = "User Inactive." };
            else
                return new Response { Status = "Success", Message = Lg.UserName };
        }
        // For new user Registration
        [Route("Api/Login/UserRegistration")]
        [HttpPost]
        public object createcontact(Registration Lvm)
        {
            try
            {
                EmployeeEntities1 db = new EmployeeEntities1();
                Employeemaster Em = new Employeemaster();
                if (Em.UserId == 0)
                {
                    Em.UserName = Lvm.UserName;
                    Em.LoginName = Lvm.LoginName;
                    Em.Password = Lvm.Password;
                    Em.Email = Lvm.Email;
                    Em.ContactNo = Lvm.ContactNo;
                    Em.Address = Lvm.Address;
                    Em.IsApporved = Lvm.IsApporved;
                    Em.Status = Lvm.Status;
                    db.Employeemasters.Add(Em);
                    db.SaveChanges();
                    return new Response { Status = "Success", Message = "SuccessFully Saved." };
                }
            }
            catch (Exception)
            {
                throw;
            }
            return new Response { Status = "Error", Message = "Invalid Data." };
        }
    }
}

Now, we will go to the Department controller with the following lines of code.

using LoginAPI.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace LoginAPI.Controllers
{
    [RoutePrefix("Api/Department")]
    public class DepartmentController : ApiController
    {
        private EmployeeEntities objEntity = new EmployeeEntities();
        [HttpGet]
        [Route("AllDepartments")]
        public IQueryable<Department> GetDepartment()
        {
            try
            {
                return objEntity.Departments;
            }
            catch (Exception)
            {
                throw;
            }
        }
        [HttpGet]
        [Route("GetDepartmentsById/{DepartmentID}")]
        public IHttpActionResult GetDepartmentById(string DepartmentID)
        {
            Department objDep = new Department();
            int ID = Convert.ToInt32(DepartmentID);
            try
            {
                objDep = objEntity.Departments.Find(ID);
                if (objDep == null)
                {
                    return NotFound();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return Ok(objDep);
        }
        [HttpPost]
        [Route("InsertDepartments")]
        public IHttpActionResult PostDepartment(Department data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                objEntity.Departments.Add(data);
                objEntity.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
            return Ok(data);
        }
        [HttpPut]
        [Route("UpdateDepartments")]
        public IHttpActionResult PutDepartment(Department department)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                Department objDep = new Department();
                objDep = objEntity.Departments.Find(department.DepartmentID);
                if (objDep != null)
                {
                    objDep.DepartmentName = department.DepartmentName;
                }
                int i = this.objEntity.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
            return Ok(department);
        }
        [HttpDelete]
        [Route("DeleteDepartments")]
        public IHttpActionResult DeleteDepartment(int id)
        {
            Department department = objEntity.Departments.Find(id);
            if (department == null)
            {
                return NotFound();
            }
            objEntity.Departments.Remove(department);
            objEntity.SaveChanges();
            return Ok(department);
        }
    }
}

Now, we will go to the Employee controller with the following lines of code.

using LoginAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace LoginAPI.Controllers
{
    [RoutePrefix("Api/Employee")]
    public class EmployeeController : ApiController
    {
        private EmployeeEntities objEntity = new EmployeeEntities();
        [HttpGet]
        [Route("AllEmployees")]
        public IQueryable<Employee> GetEmployee()
        {
            try
            {
                return objEntity.Employees;
            }
            catch (Exception)
            {
                throw;
            }
        }
        [HttpGet]
        [Route("Department")]
        public IQueryable<Department> GetDepartment()
        {
            try
            {
                return objEntity.Departments;
            }
            catch (Exception)
            {
                throw;
            }
        }
        [HttpGet]
        [Route("GetEmployeesById/{employeeId}")]
        public IHttpActionResult GetEmployeeById(string employeeId)
        {
            Employee objEmp = new Employee();
            int ID = Convert.ToInt32(employeeId);
            try
            {
                objEmp = objEntity.Employees.Find(ID);
                if (objEmp == null)
                {
                    return NotFound();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return Ok(objEmp);
        }
        [HttpPost]
        [Route("InsertEmployees")]
        public IHttpActionResult PostEmployee(Employee data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                objEntity.Employees.Add(data);
                objEntity.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
            return Ok(data);
        }
        [HttpPut]
        [Route("UpdateEmployees")]
        public IHttpActionResult PutEmployee(Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                Employee objEmp = new Employee();
                objEmp = objEntity.Employees.Find(employee.EmployeeID);
                if (objEmp != null)
                {
                    objEmp.EmployeeName = employee.EmployeeName;
                    objEmp.Department = employee.Department;
                    objEmp.MailID = employee.MailID;
                    objEmp.DOJ = employee.DOJ;
                    objEmp.Address = employee.Address;
                    objEmp.Phone = employee.Phone;
                    objEmp.Salary = employee.Salary;
                    objEmp.Age = employee.Age;
                }
                int i = this.objEntity.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
            return Ok(employee);
        }
        [HttpDelete]
        [Route("DeleteEmployees")]
        public IHttpActionResult DeleteEmployee(int id)
        {
            Employee employee = objEntity.Employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }
            objEntity.Employees.Remove(employee);
            objEntity.SaveChanges();
            return Ok(employee);
        }
    }
}

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 the Web API project and open the WebApiConfig.cs class. Here, modify the Register method with the below code.

Add namespace

using System.Web.Http.Cors;
// for JSON data into test data in POSTMAN
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// enable cors helps to connect with angular using http request
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
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.

ng new login // create your login project
cd login // location to login project
ng add @angular/material // add angular material
npm install bootstrap --save // add bootstrap
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!

Register

Register

Dashboard

Add department

Employee

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

Up Next
    Ebook Download
    View all
    Learn
    View all