ASP.NET Core là gì?

ASP.NET Core là một framework đa nền tảng (cross-platform), hiệu năng cao, mã nguồn mở để xây dựng ứng dụng web hiện đại sử dụng .NET. Framework được thiết kế cho phát triển ứng dụng quy mô lớn và có thể xử lý bất kỳ khối lượng công việc nào, phù hợp cho các ứng dụng cấp doanh nghiệp.

Các tính năng chính

Tính năngMô tả
KestrelHTTP server đa nền tảng, hiệu năng cao
Dependency InjectionContainer DI tích hợp sẵn, giảm coupling
Environment-based ConfigurationCấu hình khác nhau theo môi trường (dev, staging, prod)
Logging & MetricsGhi log phong phú, tracing và runtime metrics
BlazorUI web tương tác bằng C# — không cần JavaScript
Client-side IntegrationTích hợp liền mạch với Angular, React, Vue, Bootstrap
Minimal APIsXây dựng API nhanh với code và cấu hình tối thiểu
SignalRTính năng web thời gian thực (real-time)
gRPCDịch vụ RPC hiệu năng cao
SecurityAuthentication, authorization và data protection tích hợp sẵn
TestingDễ dàng viết unit test và integration test
ToolingNăng suất cao với Visual Studio và VS Code

Các cách xây dựng Web UI trong ASP.NET Core

ASP.NET Core Web UI
├── Razor Pages      → Phù hợp cho ứng dụng đơn giản, page-centric
├── MVC              → Mô hình MVC truyền thống
├── Blazor           → UI bằng C#, WebAssembly hoặc Server
├── Minimal APIs     → API nhanh, ít code
└── Client-side      → Angular/React/Vue + backend ASP.NET Core

Tại sao chọn ASP.NET Core?

Lý doMô tả
Unified FrameworkFramework hoàn chỉnh, tích hợp đầy đủ với mọi thành phần production-ready
Full Stack ProductivityTeam có thể làm full-stack từ frontend đến backend chỉ với một framework
Secure by DesignAuthentication, authorization, data protection tích hợp sẵn
Cloud-readyTriển khai dễ dàng lên datacenter riêng hoặc bất kỳ cloud nào
Performance & ScalabilityHiệu năng hàng đầu ngành, chịu tải cực cao
Trusted & MatureĐã được chứng minh ở quy mô lớn: Bing, Xbox, Microsoft 365, Azure

Mô hình MVC

Mô hình kiến trúc Model-View-Controller (MVC) phân tách ứng dụng thành 3 nhóm thành phần chính: Models, ViewsControllers.

Kiến trúc MVC

Lưu ý: View và Controller đều phụ thuộc vào Model. Tuy nhiên, Model không phụ thuộc vào View hay Controller. Nhờ đó, Model có thể được xây dựng và kiểm thử độc lập với phần trình bày trực quan.

Trách nhiệm của Model

Model đại diện cho trạng thái ứng dụngbusiness logic. Business logic nên được đóng gói trong model, cùng với logic persistence.

Trách nhiệm của View

View chịu trách nhiệm trình bày nội dung qua giao diện người dùng. Views sử dụng Razor view engine để nhúng code C# vào HTML. Views nên chứa logic tối thiểu — chỉ logic liên quan đến trình bày.

Trách nhiệm của Controller

Controller xử lý tương tác người dùng, làm việc với Model và chọn View để render. Controller là điểm vào đầu tiên, chịu trách nhiệm chọn Model và View phù hợp.
Mẹo: Nếu các controller action thường xuyên thực hiện các thao tác giống nhau, hãy chuyển chúng thành filters.

Các tính năng của ASP.NET Core MVC

Routing

ASP.NET Core MVC được xây dựng trên nền ASP.NET Core’s routing — một thành phần ánh xạ URL mạnh mẽ, hỗ trợ SEO và tạo URL thân thiện.

Convention-based Routing

app.MapControllerRoute(
    name: "Default",
    pattern: "{controller=Home}/{action=Index}/{id?}"
);
// URL: /Products/Details/5 → ProductsController.Details(5)

Attribute Routing

[Route("api/[controller]")]
public class ProductsController : Controller
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id) { /* ... */ }

    [HttpPost]
    public IActionResult CreateProduct([FromBody] Product product) { /* ... */ }
}

Model Binding

Model binding tự động chuyển đổi dữ liệu request (form values, route data, query string parameters, HTTP headers) thành objects mà controller có thể xử lý.
public async Task<IActionResult> Login(
    LoginViewModel model,      // Từ form/body
    string returnUrl = null   // Từ query string
)
{
    if (ModelState.IsValid)
    {
        // Xử lý với model
    }
    return View(model);
}

Model Validation

ASP.NET Core MVC hỗ trợ validation thông qua data annotation attributes. Validation chạy cả client side (trước khi post) lẫn server side (trước khi gọi action).
using System.ComponentModel.DataAnnotations;

public class LoginViewModel
{
    [Required(ErrorMessage = "Email là bắt buộc")]
    [EmailAddress(ErrorMessage = "Email không hợp lệ")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Mật khẩu là bắt buộc")]
    [DataType(DataType.Password)]
    [MinLength(8, ErrorMessage = "Mật khẩu phải có ít nhất 8 ký tự")]
    public string Password { get; set; }

    [Display(Name = "Ghi nhớ đăng nhập?")]
    public bool RememberMe { get; set; }
}
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
        // Xử lý đăng nhập thành công
    }
    return View(model); // Trả về form kèm lỗi validation
}

Dependency Injection

ASP.NET Core có hỗ trợ DI tích hợp sẵn. Trong ASP.NET Core MVC, các controller có thể yêu cầu services thông qua constructor.

Trong Controller

public class ProductsController : Controller
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
}

Trong View (dùng @inject)

@inject ISomeService ServiceName

<!DOCTYPE html>
<html lang="en">
<head>
    <title>@ServiceName.GetTitle()</title>
</head>
<body>
    <h1>@ServiceName.GetTitle()</h1>
</body>
</html>

Filters

Filters giúp đóng gói các cross-cutting concerns như xử lý exception hoặc authorization. Chúng cho phép chạy logic tùy chỉnh trước/sau action methods.
Loại FilterThứ tựMục đích
Authorization1Kiểm tra quyền truy cập
Resource2Chạy trước model binding
Action3Trước/sau action method
Exception4Xử lý exception
Result5Trước/sau ActionResult
[Authorize]
public class AccountController : Controller
{
    [HttpGet]
    [AllowAnonymous]  // Ghi đè [Authorize] cho action này
    public IActionResult Login() => View();
}

Areas

Areas cho phép chia ứng dụng ASP.NET Core MVC lớn thành các nhóm chức năng nhỏ hơn.
MyApp/
├── Areas/
│   ├── Admin/
│   │   ├── Controllers/
│   │   └── Views/
│   ├── Billing/
│   │   ├── Controllers/
│   │   └── Views/
│   └── Catalog/
│       ├── Controllers/
│       └── Views/

Web APIs

Bên cạnh việc xây dựng website, ASP.NET Core MVC còn hỗ trợ tốt việc xây dựng Web APIs phục vụ nhiều loại client khác nhau.
  • Content Negotiation: Tự động định dạng JSON hoặc XML
  • Custom Formatters: Thêm hỗ trợ format tùy chỉnh
  • HATEOAS: Tạo link cho hypermedia
  • CORS: Chia sẻ API cho nhiều ứng dụng web

Razor View Engine

Razor là ngôn ngữ template nhỏ gọn, giàu tính diễn đạt để định nghĩa views bằng code C# nhúng.
@model IEnumerable<Product>

<ul>
@for (int i = 0; i < 5; i++)
{
    <li>List item @i</li>
}
</ul>

@{
    var message = "Xin chào ASP.NET Core MVC!";
}

<p>@message</p>

Strongly Typed Views

Razor views có thể strongly typed dựa trên model. Controller truyền strongly typed model cho views, kích hoạt type checking và hỗ trợ IntelliSense.
@model IEnumerable<Product>

<ul>
@foreach (Product p in Model)
{
    <li>@p.Name</li>
}
</ul>

Tag Helpers

Tag Helpers cho phép code phía server tham gia tạo và render các phần tử HTML. Chúng mang lại trải nghiệm HTML-friendly cùng IntelliSense phong phú.
<p>
    Vui lòng <a asp-controller="Account" asp-action="Login">đăng nhập tại đây</a>.
</p>

Tải Script theo môi trường

<environment names="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>
</environment>

<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.js"
            asp-fallback-src="~/lib/jquery/dist/jquery.js"
            asp-fallback-test="window.jQuery">
    </script>
</environment>

View Components

View Components cho phép đóng gói logic rendering và tái sử dụng trong toàn bộ ứng dụng. Giống partial views nhưng có logic đi kèm.
Components/
└── CategoryMenu/
    ├── CategoryMenuViewComponent.cs
    └── Default.cshtml

Testability

Việc sử dụng interfacesdependency injection khiến framework này rất phù hợp cho unit testing, và framework còn cung cấp thêm các tính năng (như TestHost và InMemory provider cho Entity Framework) giúp integration tests nhanh và dễ dàng.

Compatibility Version

Phương thức SetCompatibilityVersion cho phép app opt-in hoặc opt-out các thay đổi breaking behavior được giới thiệu từ ASP.NET Core MVC 2.1 trở lên.
builder.Services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_10_0);

Bắt đầu

Yêu cầu

  • .NET SDK 10.0+
  • Visual Studio 2022 / VS Code / CLI

Tạo project MVC mới

# Qua CLI
dotnet new mvc -n MyApp
cd MyApp
dotnet run

Cấu trúc project

MyApp/
├── Controllers/          # Controller classes
├── Models/              # Models và ViewModels
├── Views/               # Razor Views
│   ├── _ViewStart.cshtml
│   ├── _ViewImports.cshtml
│   ├── Shared/
│   └── Products/
├── wwwroot/             # Static files (CSS, JS, images)
├── Program.cs           # Entry point của ứng dụng
└── appsettings.json     # Cấu hình

Program.cs mẫu (.NET 10)

var builder = WebApplication.CreateBuilder(args);

// Thêm MVC services
builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

// Convention-based routing
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}"
);

app.Run();

Tóm tắt

Khía cạnhChi tiết
PatternModel-View-Controller (MVC)
PlatformĐa nền tảng, Mã nguồn mở
Runtime.NET 10.0
UI EngineRazor View Engine
RoutingConvention-based + Attribute-based
ValidationData Annotations (client + server)
DIContainer tích hợp sẵn
Web APIsHỗ trợ đầy đủ (JSON/XML, CORS)
TestingTDD-friendly, DI + InMemory
TargetEnterprise Web Apps & APIs

Tài liệu tham khảo