Phát triển ứng dụng Web sử dụng Angular 12, ASP.NET Core Web API và SQL Server


Giới thiệu

Trong bài này chúng ta sẽ phát triển một ứng dụng web từ đầu sử dụng các công nghệ mới nhất theo cách dễ dàng và dễ hiểu nhất. Các công nghệ sẽ sử dụng:

  • Back-end = ASP.NET Core Web API, sử dụng .Net Core 6.0 và Visual Studio 2022
  • Database = SQL Server 
  • Front-end = ANGULAR 12.

Trước tiên, chúng ta cần tạo cơ sở dữ liệu, các bảng và thêm các bản ghi vào.

Thứ hai, chúng ta sẽ phát triển các API sử dụng ASP.NET Core Web API.

Thứ ba, Chúng ta sẽ phát triển Front-end sử dụng angular 12.

Các bước thực hiện

1. Tạo cơ sở dữ liệu

Mở SQL Server Management Studio và kết nối tới hệ quản trị cơ sở dữ liệu SQL Server được cài trên máy tính, tạo một database đặt tên là StudentDB


CREATE DATABASE StudentDB;
CREATE TABLE Student (
    StudentId int IDENTITY(1,1) NOT NULL,
    FullName nvarchar(max) NULL,
    Class nvarchar(max) NULL
);

INSERT INTO Student VALUES ('Nguyễn Văn A', 'Lớp 9A');
INSERT INTO Student VALUES ('Nguyễn Văn B','Lớp 9B');

2. Phát triển các API sử dụng ASP.NET Core Web API

Bước 1: Tạo Project WebAPI trong Visual Studio 2022

Mở Visual Studio 2022, ở màn hình khởi động kích vào nút Create a new project
Chọn template Web API trong Visual Studio

Bước 2: Đặt tên Project là WebAPI

Đặt tên Project

Bước 3: Lựa chọn các thông số cho Project

Thiết lập các tuỳ chọn cho Project

Bước 4: Cài đặt thêm các Package

Các package cài thêm:

  • Microsoft.AspNetCore.Mvc.NewtonsoftJson => hỗ trợ phần xuất dữ liệu theo định dạng JSON
  • System.Data.SqlClient => lập trình với hệ quản trị cơ sở dữ liệu SQL Server

Truy cập vào menu Project > Manage Nugets Packages …
Cài đặt thêm các Packages

Bước 5: Trong cửa sổ Solution Explorer, mở file Program.cs cập nhật thêm các dòng code

Mục đích: Kích hoạt CORS để vô hiệu hóa bảo mật và cho phép các request từ các tên miền khác. Sau khi cài đặt NewtonSoft.json, chúng ta sẽ sử dụng xuất dữ liệu ra JSON làm mặc định.


using Newtonsoft.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(c =>
{
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
builder.Services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                ).AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
                = new DefaultContractResolver());
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

app.UseRouting();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Bước 6: Tạo thư mục Models và thêm 2 class Student.cs, Department.cs


namespace WebAPI.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FullName { get; set; }
        public string Class { get; set; }
    }
}

namespace WebAPI.Models
{
    public class Department
    {
        public int DepartmentId { get; set; }
        public string DepartmentName { get; set; }
    }
}

Mở file appsettings.json và thêm chuỗi kết nối tới cơ sở dữ liệu


{
  "ConnectionStrings": {
    "StudentAppCon": "Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=StudentDB;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Bước 7: Thêm lớp StudentController.cs

Thêm lớp StudentCotroller.cs
Bây giờ, hãy thực hiện các thay đổi trong lớp StudentController.cs, ở đây chúng ta sẽ triển khai các thao tác đọc, thêm, sửa, xoá – CRUD (Create – Read – Update – Delete) bằng cách truy vấn bằng các câu lệnh SQL.


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using WebAPI.Models;

namespace WebAPI
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public StudentController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpGet]
        public JsonResult Get()
        {
            string query = "Select StudentId, FullName, Class from dbo.Student";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("StudentAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult(table);
        }
        [HttpPost]
        public JsonResult Post(Student objStudent)
        {
            string query = @"Insert into dbo.Student values
                ('" + objStudent.FullName + "','" + objStudent.Class + "')";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("StudentAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult("Added Successfully");
        }
        [HttpPut]
        public JsonResult Put(Student objStudent)
        {
            string query = @"Update dbo.Student set
                FullName = '" + objStudent.FullName + @"',
                Class='" + objStudent.Class + "' where StudentId = " + objStudent.StudentId;
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("StudentAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult("Updated Successfully");
        }


        [HttpDelete("{id}")]
        public JsonResult Delete(int id)
        {
            string query = @"Delete from dbo.Student where StudentId = " + id;
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("StudentAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult("Deleted Successfully");
        }
    }
}

Bước 8: Ấn F5 để chạy Web API

Nếu không có lỗi gì xảy ra, giao diện Swagger hiển thị ra cho phép, bạn có thể nhìn thấy danh sách các EndPoint của API. Bạn có thể kích vào nút Try it out để test thử các EndPoint.
Test API với Swagger

3. Phát triển FrontEnd với Angular12 (tiếp tục cập nhật)

Tham khảo

Khoá học lập trình Web với ASP.Net Core

Có thể bạn sẽ thích…

2 phản hồi

  1. thongvm2702 viết:

    Tiếp đi ạ, em đang cần được gỡ rối chỗ này ạ. Em cảm ơn

  2. thanhlam212 viết:

    Bài giảng rất đầy đủ và dễ hiểu ạ, mong thầy tiếp tục cập nhật phần fronend với angular ạ .em cảm ơn thầy

Trả lời

EnglishVietnamese