---
title: Razor File Compilation
description: Hướng dẫn chi tiết về Razor File Compilation trong ASP.NET Core MVC — Build-time compilation, Publish-time compilation, Runtime compilation và cách cấu hình.
---

## Razor Compilation là gì?

Razor files với extension `.cshtml` được compile tại **build time** và **publish time** sử dụng **Razor SDK**. Runtime compilation có thể được bật tùy chọn bằng cách cấu hình project.

```mermaid
flowchart TD
    A["📄 .cshtml Files"] --> B["Razor SDK"]
    B --> C["🔨 Build Time"]
    B --> D["📦 Publish Time"]
    B --> E["⚡ Runtime Compilation"]
    C --> F[".dll / Assemblies"]
    D --> F
    E --> G["🔄 Edit & Reload"]
```

> **Lưu ý:** Runtime compilation đã bị **obsolete** từ .NET 10. Không hỗ trợ cho Razor components của Blazor apps. Không hỗ trợ `global using directives` và `implicit using directives`.

---

## Razor Compilation

### Build-time và Publish-time Compilation

**Mặc định**, Razor SDK enable compilation tại thời điểm build và publish. Khi enabled, runtime compilation bổ sung cho build-time compilation, cho phép Razor files được cập nhật nếu được chỉnh sửa trong khi app đang chạy.

### So sánh các loại Compilation

|Loại compilation|Mô tả|Khi nào dùng|
|---|---|---|
|**Build-time**|Compile khi build project|Production|
|**Publish-time**|Compile khi publish project|Deployment|
|**Runtime**|Compile khi app đang chạy|Development (đã obsolete)|

### Hot Reload thay thế Runtime Compilation

```mermaid
flowchart LR
    A[".NET Hot Reload"] --> B["Ưu tiên cho Development"]
    C["Runtime Compilation"] --> D["Obsolete từ .NET 10"]
```

> **Lưu ý:** Runtime compilation **vô hiệu hóa** `.NET Hot Reload`. Thay vào đó, Microsoft khuyến nghị sử dụng **Hot Reload** cho development scenarios.

### Khuyến nghị

|Scenario|Khuyến nghị|
|---|---|
|Production|Default build-time compilation|
|Development|Hot Reload (.NET)|
|Runtime Compilation|Deprecated, không khuyến khích|

Xem thêm: [Razor runtime compilation is obsolete](https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/10/razor-runtime-compilation-obsolete)

---

## Enable Runtime Compilation cho tất cả Environments

### Bước 1: Cài đặt NuGet Package

```bash
dotnet add package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
```

### Bước 2: Cấu hình trong Program.cs

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages()
    .AddRazorRuntimeCompilation();

var app = builder.Build();

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

app.MapRazorPages();

app.Run();
```

---

## Enable Runtime Compilation có điều kiện

Runtime compilation có thể được enable có điều kiện, đảm bảo rằng published output:

- Sử dụng compiled views
- Không enable file watchers trong production

### Cách 1: Kiểm tra Environment trong Program.cs

```csharp
var builder = WebApplication.CreateBuilder(args);

var mvcBuilder = builder.Services.AddRazorPages();

if (builder.Environment.IsDevelopment())
{
    mvcBuilder.AddRazorRuntimeCompilation();
}

var app = builder.Build();

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

app.MapRazorPages();

app.Run();
```

### Cách 2: Hosting Startup Assembly

Runtime compilation cũng có thể được enable với **hosting startup assembly**. Cách này không cần thay đổi code trong `Program.cs`.

#### Yêu cầu

- Install `Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation` NuGet package
- Đặt `ASPNETCORE_ENVIRONMENT` là `"Development"`
- Set `ASPNETCORE_HOSTINGSTARTUPASSEMBLIES` là `"Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"`

#### launchSettings.json

```json
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:7098",
      "sslPort": 44332
    }
  },
  "profiles": {
    "ViewCompilationSample": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7173;http://localhost:5251",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"
      }
    }
  }
}
```

### Cách hoạt động

At runtime, ASP.NET Core tìm kiếm một **assembly-level HostingStartup attribute** trong `Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation`. HostingStartup attribute chỉ định code startup để execute và enable runtime compilation.

---

## Enable Runtime Compilation cho Razor Class Library

### Kịch bản

Một Razor Pages project tham chiếu đến **Razor Class Library (RCL)** tên `MyClassLib`. RCL chứa file `_Layout.cshtml` được sử dụng bởi MVC và Razor Pages projects.

### Bước 1: Enable Runtime Compilation có điều kiện

Làm theo hướng dẫn **Enable runtime compilation conditionally** ở trên.

### Bước 2: Cấu hình MvcRazorRuntimeCompilationOptions

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{
    var libraryPath = Path.GetFullPath(
        Path.Combine(builder.Environment.ContentRootPath, "..", "MyClassLib"));

    options.FileProviders.Add(
        new PhysicalFileProvider(libraryPath));
});

var app = builder.Build();
```

### Giải thích

```mermaid
flowchart TD
    A["MvcRazorRuntimeCompilationOptions"] --> B["PhysicalFileProvider"]
    B --> C["MyClassLib Path"]
    C --> D["RCL .cshtml Files"]
    D --> E["Runtime Compilation"]
```

- Code trên xây dựng **absolute path** đến `MyClassLib` RCL
- `PhysicalFileProvider` API được sử dụng để locate directories và files tại absolute path đó
- `PhysicalFileProvider` instance được thêm vào **file providers collection**, cho phép truy cập RCL's `.cshtml` files

---

## Razor SDK Properties

### Các Property quan trọng

|Property|Mô tả|Giá trị mặc định|
|---|---|---|
|`RazorCompileOnBuild`|Compile Razor tại build time|`true`|
|`RazorCompileOnPublish`|Compile Razor tại publish time|`true`|

### Tắt Compilation trong Project File

```xml
<PropertyGroup>
  <RazorCompileOnBuild>false</RazorCompileOnBuild>
  <RazorCompileOnPublish>false</RazorCompileOnPublish>
</PropertyGroup>
```

---

## So sánh: Build vs Runtime Compilation

```mermaid
flowchart LR
    A["Razor Compilation"] --> B["Build-time"]
    A --> C["Publish-time"]
    A --> D["Runtime"]

    B --> B1["✅ Fast production"]
    B1 --> B2["Edit → Build lại"]
    C --> C1["✅ Optimized deploy"]
    D --> D1["⚠️ Obsolete"]
    D1 --> D2["Use Hot Reload"]
```

---

## Tài liệu tham khảo

- [RazorCompileOnBuild and RazorCompileOnPublish](https://learn.microsoft.com/en-us/aspnet/core/razor-pages/sdk#properties)
- [Razor Pages architecture and concepts in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/razor-pages/)
- [Views in ASP.NET Core MVC](https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview)
- [ASP.NET Core Razor SDK](https://learn.microsoft.com/en-us/aspnet/core/razor-pages/sdk)
- [Razor runtime compilation is obsolete](https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/10/razor-runtime-compilation-obsolete)
