Razor Compilation là gì?

Razor files với extension .cshtml được compile tại build timepublish 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.
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 directivesimplicit 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 compilationMô tảKhi nào dùng
Build-timeCompile khi build projectProduction
Publish-timeCompile khi publish projectDeployment
RuntimeCompile khi app đang chạyDevelopment (đã obsolete)

Hot Reload thay thế Runtime Compilation

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ị

ScenarioKhuyến nghị
ProductionDefault build-time compilation
DevelopmentHot Reload (.NET)
Runtime CompilationDeprecated, không khuyến khích
Xem thêm: Razor runtime compilation is obsolete

Enable Runtime Compilation cho tất cả Environments

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

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

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

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

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"Development"
  • Set ASPNETCORE_HOSTINGSTARTUPASSEMBLIES"Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"

launchSettings.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

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

  • 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

PropertyMô tảGiá trị mặc định
RazorCompileOnBuildCompile Razor tại build timetrue
RazorCompileOnPublishCompile Razor tại publish timetrue

Tắt Compilation trong Project File

<PropertyGroup>
  <RazorCompileOnBuild>false</RazorCompileOnBuild>
  <RazorCompileOnPublish>false</RazorCompileOnPublish>
</PropertyGroup>

So sánh: Build vs Runtime Compilation


Tài liệu tham khảo