Xac thuc khong can viet them code trong API .NET

Ngay 4 thang 7, 2026 · Doc trong 5 phut · Cap nhat ngay 10 thang 7, 2026

Chu de: dotnet, csharp, strong-types, type-safety, api-design, validations

Trong mot du an truoc day, toi nhan ra mot van de lien quan den viec xac thuc du lieu. Cu the hon, toi phai viet cung mot quy tac bao nhieu lan.

Hay xem endpoint dat hang sau day. Viec xac thuc xuat hien o ba noi:

  1. Data annotations tu dong xac thuc DTO cua request va cung cap schema JSON cho OpenAPI.
  2. Controller kiem tra nhung quy tac khong the bieu dien trong OpenAPI, nham that bai som truoc khi thuc hien truy van den co so du lieu.
  3. Service chua logic nghiep vu van phai kiem tra lai, vi no co the duoc goi tu mot noi khac, chang han tu mot background job sau khi lay entity tu co so du lieu.

Ba noi khac nhau rat de tao ra loi chi vi ban quen cap nhat mot trong so do.

public record CreateOrderRequest(
    [EmailAddress] string CustomerEmail,
    string ProductCode,
    [Range(1, int.MaxValue)] int Quantity);

[HttpPost]
[ProducesResponseType<OrderResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<OrderResponse>> Create(CreateOrderRequest request)
{
    // Can phai phan tich, vi data annotations khong thay doi kieu du lieu.
    if (!MailAddress.TryCreate(request.CustomerEmail, out _))
        return ValidationProblem("Email cua khach hang khong hop le.");

    try
    {
        var order = await orders.PlaceAsync(request.CustomerEmail, request.ProductCode, request.Quantity);
        return Ok(OrderResponse.From(order));
    }
    catch (UnknownProductException)
    {
        return ValidationProblem("Khong co san pham nao khop voi ma nay.");
    }
    catch (OutOfStockException)
    {
        return ValidationProblem("Khong du hang ton kho de hoan tat don hang.");
    }
}

Data annotations xac thuc dia chi email, nhung gia tri ban van nhan duoc chi la mot chuoi. Tuong tu, so nguyen duoc xac thuc la so duong, nhung ban khong the su dung truc tiep bao dam do. Sau do la service:

public async Task<Order> PlaceAsync(string customerEmail, string productCode, int quantity)
{
    // Van phai kiem tra, du controller da kiem tra tat ca nhung dieu nay.
    if (string.IsNullOrWhiteSpace(productCode))
        throw new ArgumentException("Ma san pham la bat buoc.", nameof(productCode));
    if (quantity <= 0)
        throw new ArgumentOutOfRangeException(nameof(quantity), "So luong phai lon hon 0.");

    if (!await catalog.ContainsAsync(productCode))
        throw new UnknownProductException(productCode);

    // Xu ly nghiep vu thuc su.
}

PlaceAsync cuoi cung van phai dam bao moi thu hoat dong dung. No co the duoc goi tu controller, background worker hoac mot endpoint khac. Vi vay, no phai xac thuc lai.

Phan tich thay vi xac thuc lap lai

Giai phap nay bat nguon tu mot y tuong cu trong lap trinh ham: thay vi kiem tra mot gia tri roi tiep tuc truyen cung kieu du lieu long leo, hay chuyen gia tri do mot lan duy nhat sang mot kieu khong the bieu dien trang thai khong hop le.

Mot int vua vuot qua kiem tra > 0 van chi la mot int. Bao dam do bi bo di ngay khi viec kiem tra thanh cong, nen phuong thuc tiep theo lai phai kiem tra tu dau. Trong khi do, Positive<int> luu bao dam nay ngay trong kieu du lieu, va trinh bien dich se ap dung no o moi noi su dung ve sau.

Do la ly do toi xay dung goi Kalicz.StrongTypes. Day la mot bo nho cac kieu C#. Vi du co NonEmptyString, Email, NonEmptyEnumerable<T>, cac kieu so nhu Positive<T>, NonNegative<T> cung nhieu kieu va tien ich huu dung khac.

Result<T, TError> cung la mot kieu rat huu ich, co the bieu dien trang thai thanh cong hoac loi cua thao tac. Ngoai ra, Maybe<T> giup ban bieu dien ba trang thai trong API. Chang han, khi cap nhat mot gia tri thanh mot gia tri moi, xoa gia tri, hoac khong cap nhat gia tri.

Thu vien con nhieu thanh phan khac. Neu quan tam, ban co the xem tai GitHub. Thu vien se tiep tuc duoc mo rong. Vi du, Interval<T> se giup bieu dien khoang bat dau va ket thuc, dong thoi xac thuc rang diem ket thuc nam sau diem bat dau.

Phan khong can them code

Chi can mot dong de cai dat:

dotnet add package Kalicz.StrongTypes

Sau do, ban co the bat dau su dung cac kieu nay:

public record CreateOrderRequest(
    Email CustomerEmail,
    NonEmptyString ProductCode,
    Positive<int> Quantity);

[HttpPost]
[ProducesResponseType<OrderResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<OrderResponse>> Create(CreateOrderRequest request)
{
    // Khong can xac thuc tai day.
    var result = await orders.PlaceAsync(request.CustomerEmail, request.ProductCode, request.Quantity);

    if (result.Error is { } error)
        return error switch
        {
            PlaceOrderError.UnknownProduct => FieldProblem(nameof(request.ProductCode), "Khong co san pham nao khop voi ma nay."),
            PlaceOrderError.OutOfStock => FieldProblem(nameof(request.Quantity), "Khong du hang ton kho de hoan tat don hang."),
        };

    return Ok(OrderResponse.From(result.Success!));
}

private ActionResult FieldProblem(string field, string message)
{
    ModelState.AddModelError(field, message);
    return ValidationProblem(ModelState);
}

Data annotations da bien mat. Viec chuyen doi sang MailAddress cung khong con. Moi thong tin ve gia tri nay nam trong kieu du lieu. Va vi phuong thuc tra ve mot ket qua thay vi nem exception, trinh bien dich biet chinh xac nhung loi nao co the xay ra.

Tat ca cac kieu deu ho tro chuyen doi qua lai voi JSON ngay tu dau. Schema OpenAPI cung duoc cap nhat dung. Chi can cai dat goi Kalicz.StrongTypes.OpenApi.Swashbuckle hoac bien the Microsoft.AspNetCore.OpenApi, sau do dang ky:

// Program.cs - cai dat Kalicz.StrongTypes.OpenApi.Swashbuckle, sau do goi mot lan
builder.Services.AddSwaggerGen(options => options.AddStrongTypes());

Request o tren se tao ra dung cac rang buoc ma client can:

{
  "customerEmail": { "type": "string", "format": "email", "minLength": 1, "maxLength": 254 },
  "productCode": { "type": "string", "minLength": 1 },
  "quantity": { "type": "integer", "format": "int32", "minimum": 0, "exclusiveMinimum": true }
}

Chu ky phuong thuc tro thanh tai lieu

Uu diem de thay nhat la code tro nen de hieu hon nhieu. Moi phuong thuc co the neu ro yeu cau thuc su:

// Truoc: moi noi goi phai kiem tra lai, moi nguoi doc deu phai doan.
Task<Order> PlaceAsync(string email, string code, int quantity);

// Sau: chu ky la hop dong.
Task<Result<Order, PlaceOrderError>> PlaceAsync(Email email, NonEmptyString code, Positive<int> quantity);

Chu ky thu hai tra loi nhung cau hoi ma chu ky dau tien buoc ban phai tim hieu: ma san pham khong the rong, so luong khong the bang 0. Nguoi review khong con phai hoi “neu so luong la am ba thi sao?”, vi cau hoi do khong con phu hop voi kieu du lieu.

Cac quy tac nghiep vu co the that bai hop le cung duoc xu ly bang Result<T, TError>. Loi tro thanh mot gia tri trong chu ky thay vi mot exception bat ngo:

public async Task<Result<Order, PlaceOrderError>> PlaceAsync(Email email, NonEmptyString code, Positive<int> quantity)
{
    if (!await catalog.ContainsAsync(code))
        return PlaceOrderError.UnknownProduct;

    if (!await inventory.HasStockAsync(code, quantity))
        return PlaceOrderError.OutOfStock;

    return new Order(email, code, quantity);
}

Quan trong hon ca, khi doc lai code sau nam thang, ban khong can nho lai boi canh. Ban cung khong can tim hieu gia tri den tu dau va co the chua gi. Nhan vien moi cung khong phai lien tuc hoi lai. Code tu mo ta chinh xac dieu dang dien ra, bo sung ro rang va boi canh.

Cac kieu du lieu di den co so du lieu

Khi nap entity vao context bang EF Core, ban thuong phai xac thuc lai. Tuy nhien, voi goi Kalicz.StrongTypes.EfCore, cac strong type tro thanh thuoc tinh truc tiep cua entity. Chi can mot lenh tren options builder de gan value converter cho tung kieu:

public sealed class Order
{
    public Guid Id { get; init; }
    public Email CustomerEmail { get; init; }
    public NonEmptyString ProductCode { get; init; }
    public Positive<int> Quantity { get; init; }
}

// Program.cs - dang ky StrongTypes cho db context.
services.AddDbContext<ShopDbContext>(options => options
    .UseNpgsql(connectionString)
    .UseStrongTypes());

Cot trong co so du lieu van la varchar hoac int thong thuong, khong co thay doi nao ve cach luu tru. Tuy nhien, EF Core se khong cho phep luu gia tri khong hop le. Neu ban thu nap gia tri khong hop le tu co so du lieu, he thong se bao loi ro rang thay vi am tham tra ve null. Thong tin da duoc phan tich vi the duoc giu lai mai mai. Ban co the nap entity va goi PlaceAsync mot cach an toan.

It truong hop dac biet hon, it bai kiem thu hon

So luong unit test can thiet da giam dang ke. Cac truong hop bien nay don gian la khong con co the xay ra. Ban khong the truyen null, chuoi rong hoac chuoi chi co khoang trang vao NonEmptyString. Ban cung khong the truyen -1 vao so luong. Phan con lai la cac bai kiem thu ve hanh vi, nhung bai kiem thu thuc su co y nghia.

API de tao cac kieu nay cung the hien ro y dinh:

NonEmptyString name = NonEmptyString.Create(input);    // nem loi neu khong hop le
NonEmptyString? safe = NonEmptyString.TryCreate(input); // null neu khong hop le
NonEmptyString? fluent = input.AsNonEmpty();              // tuong tu, duoi dang extension

Voi cac thuoc tinh ban van muon kiem tra, property-based testing cho phep ban viet mot phuong thuc kiem thu va chay no voi hang tram gia tri khac nhau. Goi Kalicz.StrongTypes.FsCheck tao ra cac gia tri strong type hop le cho property-based test, vi the bo tao du lieu tuan theo cung cac bat bien ma code cua ban su dung.

Hay thu ngay

Toan bo thay doi co the tom tat trong mot hinh anh: xac thuc lap lai o moi tang so voi phan tich mot lan tai bien JSON.

So sanh hai mo hinh: khong co StrongTypes, moi tang xac thuc lai cung mot chuoi; voi StrongTypes, gia tri duoc phan tich mot lan tai bien JSON va NonEmptyString duy tri bao dam qua controller, service va co so du lieu

Ngay ca backend cua chinh trang web nay cung chay tren StrongTypes: request DTO, domain event va trang thai entity. Neu cach tiep can nay phu hop voi ban, trang StrongTypes co cac so do va nhieu vi du hon; ma nguon nam tren GitHub, con goi thu vien co tren NuGet.

Hay bat dau voi mot request record. Xoa cac doan kiem tra da tro nen thua. Ban se nhanh chong nhan ra rang minh muon ap dung cach nay o moi noi.