Khoá học web cho nhà máy, bài 6: C# và ASP.NET Core Web API cho thiết bị

Tạo Web API bằng ASP.NET Core, kết nối SQL Server với Entity Framework Core, viết controller CRUD cho thiết bị có phân trang, kiểm tra dữ liệu, mã trạng thái HTTP và nối giao diện React qua proxy của Vite.

· 8 phút đọc#khoá học#C##ASP.NET Core#Web API#Entity Framework Core

Máy chủ là nơi nghiệp vụ và quyền hạn sống. Giao diện React chỉ là một khách hàng gọi vào. Bài này dựng API đầu tiên: quản lý thiết bị (core.Assets) với đầy đủ thêm, sửa, xoá, tìm kiếm, phân trang.

1. C# trong 10 phút

Nếu bạn đã biết JavaScript, C# khác chủ yếu ở kiểu tĩnh:

int count = 3;                       // kiểu số nguyên
string name = "Motor băng tải";      // chuỗi
decimal qty = 12.5m;                 // số thập phân chính xác (hậu tố m)
DateTime utcNow = DateTime.UtcNow;   // thời điểm UTC
DateOnly due = new(2026, 12, 9);     // ngày thuần
string? line = null;                 // ? nghĩa là có thể null
var list = new List<string> { "A", "B" };

record AssetDto(int Id, string Code, string Name);   // kiểu dữ liệu bất biến, gọn

var names = assets.Where(a => a.Status == 1).Select(a => a.Name).ToList();   // LINQ

LINQ (Where, Select, OrderBy, GroupBy...) tương ứng với filter, map, sort của JavaScript, và quan trọng hơn, Entity Framework dịch LINQ thành SQL.

2. Tạo dự án

dotnet new webapi -n Factory.Api --use-controllers
cd Factory.Api
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-ef

Mẫu webapi có sẵn dự án chạy được. Xoá tệp WeatherForecast mẫu. Cấu trúc ta hướng tới:

Factory.Api/
├─ Program.cs
├─ appsettings.json
├─ Data/        FactoryDbContext.cs, Entities/
├─ Dtos/        các kiểu dữ liệu vào/ra API
└─ Controllers/ AssetsController.cs ...

3. Chuỗi kết nối và bí mật

Chuỗi kết nối chứa mật khẩu không được nằm trong Git. Dùng user-secrets khi phát triển:

dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:Factory" "Server=localhost;Database=FactoryDb;User Id=sa;Password=<MatKhau>;TrustServerCertificate=True"

Khi triển khai thật, dùng biến môi trường hoặc kho bí mật (key vault) và tài khoản SQL chỉ có quyền cần thiết (không dùng sa). Nếu SQL Server cùng máy chủ Windows, có thể dùng Trusted_Connection=True (xác thực Windows).

4. Thực thể và DbContext

Ta viết thực thể bằng tay cho gọn và dễ hiểu (có thể dùng dotnet ef dbcontext scaffold để sinh tự động khi cơ sở dữ liệu có sẵn nhiều bảng).

Data/Entities/Asset.cs:

namespace Factory.Api.Data.Entities;

public class Asset
{
    public int Id { get; set; }
    public string Code { get; set; } = "";
    public string Name { get; set; } = "";
    public int? ParentId { get; set; }
    public string AssetType { get; set; } = "";
    public string? Line { get; set; }
    public byte Status { get; set; }
    public DateOnly? InstalledOn { get; set; }
    public decimal? IdealCycleSec { get; set; }
}

Data/FactoryDbContext.cs:

using Factory.Api.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace Factory.Api.Data;

public class FactoryDbContext(DbContextOptions<FactoryDbContext> options) : DbContext(options)
{
    public DbSet<Asset> Assets => Set<Asset>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Asset>(e =>
        {
            e.ToTable("Assets", "core");
            e.Property(x => x.Code).HasMaxLength(30);
            e.Property(x => x.Name).HasMaxLength(100);
            e.Property(x => x.IdealCycleSec).HasPrecision(9, 3);
            e.HasIndex(x => x.Code).IsUnique();
        });
    }
}

Ta không dùng migration ở đây vì cơ sở dữ liệu đã được tạo bằng script SQL ở bài 4 (cách phổ biến trong phần mềm công nghiệp, nơi DBA kiểm soát schema). ToTable("Assets", "core") ánh xạ lớp C# vào bảng có sẵn.

5. DTO: đừng đưa thẳng thực thể ra ngoài

DTO (Data Transfer Object) là hình dạng dữ liệu của API. Tách DTO khỏi thực thể để không vô tình lộ cột nội bộ và để đổi cơ sở dữ liệu mà không phá hợp đồng API.

Dtos/AssetDtos.cs:

using System.ComponentModel.DataAnnotations;

namespace Factory.Api.Dtos;

public record AssetDto(int Id, string Code, string Name, int? ParentId,
                       string AssetType, string? Line, byte Status,
                       DateOnly? InstalledOn, decimal? IdealCycleSec);

public class AssetInput
{
    [Required, StringLength(30)]  public string Code { get; set; } = "";
    [Required, StringLength(100)] public string Name { get; set; } = "";
    public int? ParentId { get; set; }
    [Required, StringLength(30)]  public string AssetType { get; set; } = "";
    [StringLength(30)]            public string? Line { get; set; }
    [Range(0, 3)]                 public byte Status { get; set; }
    public DateOnly? InstalledOn { get; set; }
    [Range(0.001, 3600)]          public decimal? IdealCycleSec { get; set; }
}

public record PagedResult<T>(IReadOnlyList<T> Items, int Total);

Các thuộc tính [Required], [Range]... được ASP.NET Core kiểm tra tự động; dữ liệu sai trả về 400 Bad Request kèm chi tiết, không cần viết if tay.

6. Controller

Controllers/AssetsController.cs:

using Factory.Api.Data;
using Factory.Api.Data.Entities;
using Factory.Api.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Factory.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AssetsController(FactoryDbContext db) : ControllerBase
{
    private static AssetDto ToDto(Asset a) =>
        new(a.Id, a.Code, a.Name, a.ParentId, a.AssetType, a.Line, a.Status, a.InstalledOn, a.IdealCycleSec);

    // GET /api/assets?q=motor&page=1&pageSize=20
    [HttpGet]
    public async Task<ActionResult<PagedResult<AssetDto>>> List(
        string? q, int page = 1, int pageSize = 20)
    {
        page = Math.Max(page, 1);
        pageSize = Math.Clamp(pageSize, 1, 100);

        var query = db.Assets.AsNoTracking();
        if (!string.IsNullOrWhiteSpace(q))
            query = query.Where(a => a.Code.Contains(q) || a.Name.Contains(q));

        var total = await query.CountAsync();
        var items = await query
            .OrderBy(a => a.Code)
            .Skip((page - 1) * pageSize).Take(pageSize)
            .Select(a => ToDto(a))
            .ToListAsync();

        return new PagedResult<AssetDto>(items, total);
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<AssetDto>> Get(int id)
    {
        var a = await db.Assets.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
        return a is null ? NotFound() : ToDto(a);
    }

    [HttpPost]
    public async Task<ActionResult<AssetDto>> Create(AssetInput input)
    {
        var a = new Asset();
        Apply(a, input);
        db.Assets.Add(a);
        try { await db.SaveChangesAsync(); }
        catch (DbUpdateException ex) when (IsUniqueViolation(ex))
        { return Conflict(new { message = $"Mã thiết bị '{input.Code}' đã tồn tại." }); }

        return CreatedAtAction(nameof(Get), new { id = a.Id }, ToDto(a));
    }

    [HttpPut("{id:int}")]
    public async Task<IActionResult> Update(int id, AssetInput input)
    {
        var a = await db.Assets.FindAsync(id);
        if (a is null) return NotFound();
        Apply(a, input);
        try { await db.SaveChangesAsync(); }
        catch (DbUpdateException ex) when (IsUniqueViolation(ex))
        { return Conflict(new { message = $"Mã thiết bị '{input.Code}' đã tồn tại." }); }
        return NoContent();
    }

    [HttpDelete("{id:int}")]
    public async Task<IActionResult> Delete(int id)
    {
        var a = await db.Assets.FindAsync(id);
        if (a is null) return NotFound();
        db.Assets.Remove(a);
        try { await db.SaveChangesAsync(); }
        catch (DbUpdateException)
        { return Conflict(new { message = "Thiết bị đã có dữ liệu liên quan (lệnh bảo trì, sản lượng...), không xoá được." }); }
        return NoContent();
    }

    private static void Apply(Asset a, AssetInput i)
    {
        a.Code = i.Code.Trim();
        a.Name = i.Name.Trim();
        a.ParentId = i.ParentId;
        a.AssetType = i.AssetType;
        a.Line = i.Line;
        a.Status = i.Status;
        a.InstalledOn = i.InstalledOn;
        a.IdealCycleSec = i.IdealCycleSec;
    }

    // 2601, 2627: vi phạm UNIQUE trong SQL Server
    private static bool IsUniqueViolation(DbUpdateException ex) =>
        ex.InnerException is Microsoft.Data.SqlClient.SqlException { Number: 2601 or 2627 };
}

Những điểm đáng học:

  • Bất đồng bộ (async/await, ToListAsync): máy chủ không bị treo khi chờ cơ sở dữ liệu. Giống async/await ở bài 2.
  • AsNoTracking() cho truy vấn chỉ đọc: nhanh hơn vì EF không theo dõi thay đổi.
  • Phân trang ở phía máy chủ (Skip/Take) và giới hạn pageSize; không bao giờ trả cả bảng.
  • Mã trạng thái HTTP có nghĩa: 200 OK, 201 Created (kèm đường dẫn), 204 No Content, 400 dữ liệu sai, 404 không có, 409 xung đột (trùng mã, ràng buộc khoá ngoại).
  • Chuỗi tìm kiếm đi qua tham số hoá của EF, nên không bị SQL injection. Không bao giờ ghép chuỗi người dùng vào câu SQL.

7. Program.cs

using Factory.Api.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddDbContext<FactoryDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Factory")));

var app = builder.Build();

app.UseExceptionHandler();   // lỗi không bắt được trả về dạng ProblemDetails, không lộ stack trace
app.MapControllers();
app.Run();

Chạy với địa chỉ cố định để bước sau cấu hình proxy dễ:

dotnet run --urls http://localhost:5080

Thử bằng curl hoặc Postman:

curl "http://localhost:5080/api/assets?q=motor"
curl -X POST http://localhost:5080/api/assets -H "Content-Type: application/json" \
  -d '{"code":"CNV-02","name":"Băng tải 2","assetType":"Machine","line":"Line 1","status":1}'

Gửi thiếu code bạn sẽ nhận 400 với danh sách lỗi.

8. Nối React qua proxy của Vite

Trong factory-web/vite.config.js:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: { proxy: { "/api": "http://localhost:5080" } },
});

Mọi gọi fetch("/api/...") từ trình duyệt đến Vite (cổng 5173) sẽ được chuyển tới API (cổng 5080). Không cần cấu hình CORS khi phát triển, và hàm api() ở bài 2 dùng được ngay.

Khi triển khai thật, thường đặt React (tệp tĩnh) và API sau cùng một tên miền (qua IIS, Nginx hoặc YARP), để giữ nguyên đường dẫn /api và tránh CORS. Nếu khác tên miền, cần bật CORS rõ ràng cho đúng tên miền giao diện.

Bài tập

  1. Thêm điểm cuối GET /api/assets/tree trả về cây thiết bị (gợi ý: lấy toàn bộ thiết bị rồi dựng cây trong bộ nhớ bằng ToLookup theo ParentId).
  2. Thêm lọc theo line và status vào danh sách, kèm tham số sắp xếp sort=name hoặc sort=-code.
  3. Thêm thực thể Material (erp.Materials) và MaterialsController với danh sách và tạo mới theo cùng mẫu.
  4. Thêm thuộc tính [Range(0,3)] đã có cho Status. Gửi status: 9 và đọc nội dung 400 nhận được.

Tóm tắt

  • C# là ngôn ngữ kiểu tĩnh; LINQ được EF Core dịch thành SQL.
  • Mô hình: Entity (ánh xạ bảng) → DTO (hợp đồng API) → Controller (HTTP).
  • Kiểm tra dữ liệu bằng thuộc tính, trả mã HTTP đúng nghĩa, phân trang ở máy chủ, không ghép chuỗi SQL.
  • Bí mật (mật khẩu) nằm ngoài Git: user-secrets, biến môi trường.
  • Bài 7 thêm đăng nhập và phân quyền, vì hiện giờ ai cũng gọi được API này.