scalar

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Scalar

Scalar

Core Principles

核心原则

  1. Scalar replaces Swagger UI — Scalar is the recommended API documentation UI for .NET 10. Faster rendering, built-in dark mode, code generation for dozens of languages, and full OpenAPI 3.1 support.
  2. Development only by default — Wrap
    MapScalarApiReference()
    in an
    IsDevelopment()
    check. API documentation exposes internal structure. If needed in production, add authorization.
  3. Disable the proxy for sensitive APIs — Scalar's "Try It" feature routes through
    proxy.scalar.com
    by default. Disable it with
    .WithProxy(null)
    to keep auth headers local.
  4. Security schemes come from OpenAPI — Scalar reads security schemes from the OpenAPI document. Configure them via document transformers, not in Scalar directly.
  1. Scalar替代Swagger UI —— Scalar是.NET 10推荐使用的API文档UI,具备更快的渲染速度、内置深色模式、支持数十种语言的代码生成功能,且完全兼容OpenAPI 3.1。
  2. 默认仅用于开发环境 —— 将
    MapScalarApiReference()
    包裹在
    IsDevelopment()
    检查中。API文档会暴露内部结构,若需在生产环境使用,需添加授权验证。
  3. 敏感API禁用代理 —— Scalar的"Try It"功能默认通过
    proxy.scalar.com
    路由请求。使用
    .WithProxy(null)
    禁用代理,以确保认证头信息仅在本地传输。
  4. 安全方案源自OpenAPI —— Scalar从OpenAPI文档中读取安全方案,需通过文档转换器进行配置,而非直接在Scalar中设置。

Patterns

实践模式

Basic Setup

基础设置

csharp
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();  // UI at /scalar/v1
}

app.Run();
csharp
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();  // UI 访问路径为 /scalar/v1
}

app.Run();

Customized Configuration

自定义配置

csharp
app.MapScalarApiReference(options =>
{
    options
        .WithTitle("Checkout API")
        .WithTheme(ScalarTheme.Mars)
        .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
        .WithPreferredScheme("Bearer")
        .WithProxy(null)  // Disable external proxy
        .WithSidebar(true);
});
csharp
app.MapScalarApiReference(options =>
{
    options
        .WithTitle("Checkout API")
        .WithTheme(ScalarTheme.Mars)
        .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
        .WithPreferredScheme("Bearer")
        .WithProxy(null)  // 禁用外部代理
        .WithSidebar(true);
});

Authentication Prefill (Development Only)

身份验证预填充(仅开发环境)

Pre-fill credentials so developers don't have to paste tokens manually. The OpenAPI document must already include the security scheme via a document transformer.
csharp
if (app.Environment.IsDevelopment())
{
    app.MapScalarApiReference(options =>
    {
        options
            .WithPreferredScheme("Bearer")
            .AddHttpAuthentication("Bearer", auth =>
            {
                auth.Token = "dev-only-test-token";
            });
    });
}
Other auth types:
csharp
// API Key
options.WithApiKeyAuthentication(apiKey =>
{
    apiKey.Token = "dev-api-key";
});

// OAuth2
options.WithOAuth2Authentication(oauth =>
{
    oauth.ClientId = "your-client-id";
    oauth.Scopes = ["openid", "profile"];
});
预填充凭证,避免开发者手动粘贴令牌。OpenAPI文档需已通过文档转换器包含安全方案。
csharp
if (app.Environment.IsDevelopment())
{
    app.MapScalarApiReference(options =>
    {
        options
            .WithPreferredScheme("Bearer")
            .AddHttpAuthentication("Bearer", auth =>
            {
                auth.Token = "dev-only-test-token";
            });
    });
}
其他认证类型:
csharp
// API Key
options.WithApiKeyAuthentication(apiKey =>
{
    apiKey.Token = "dev-api-key";
});

// OAuth2
options.WithOAuth2Authentication(oauth =>
{
    oauth.ClientId = "your-client-id";
    oauth.Scopes = ["openid", "profile"];
});

Available Themes

可用主题

csharp
// ScalarTheme options: Default, Moon, Purple, BluePlanet, Saturn, Mars, DeepSpace, Kepler, Solarized, Laserwave
options.WithTheme(ScalarTheme.Mars);
csharp
// ScalarTheme 可选值: Default, Moon, Purple, BluePlanet, Saturn, Mars, DeepSpace, Kepler, Solarized, Laserwave
options.WithTheme(ScalarTheme.Mars);

Multiple API Documents

多API文档支持

csharp
// Register multiple OpenAPI documents
builder.Services.AddOpenApi("v1");
builder.Services.AddOpenApi("v2-beta");

// Scalar picks them up automatically
app.MapOpenApi();
app.MapScalarApiReference();
// Available at /scalar/v1 and /scalar/v2-beta
Or configure documents explicitly:
csharp
app.MapScalarApiReference(options =>
{
    options
        .AddDocument("v1", "Production API")
        .AddDocument("v2-beta", "Beta API", isDefault: true);
});
csharp
// 注册多个OpenAPI文档
builder.Services.AddOpenApi("v1");
builder.Services.AddOpenApi("v2-beta");

// Scalar会自动识别
app.MapOpenApi();
app.MapScalarApiReference();
// 访问路径为 /scalar/v1 和 /scalar/v2-beta
也可显式配置文档:
csharp
app.MapScalarApiReference(options =>
{
    options
        .AddDocument("v1", "Production API")
        .AddDocument("v2-beta", "Beta API", isDefault: true);
});

Custom Route Prefix

自定义路由前缀

csharp
// Default is /scalar/{documentName}
app.MapScalarApiReference("/api-docs");
// Now at /api-docs/v1
csharp
// 默认路径为 /scalar/{documentName}
app.MapScalarApiReference("/api-docs");
// 现在访问路径为 /api-docs/v1

Production with Authorization

带授权的生产环境配置

csharp
// When partners need access to docs in production
app.MapOpenApi().RequireAuthorization("ApiDocs");
app.MapScalarApiReference().RequireAuthorization("ApiDocs");
csharp
// 当合作伙伴需要在生产环境访问文档时
app.MapOpenApi().RequireAuthorization("ApiDocs");
app.MapScalarApiReference().RequireAuthorization("ApiDocs");

Force Dark Mode

强制深色模式

csharp
options.ForceDarkMode();
csharp
options.ForceDarkMode();

Classic Layout (Swagger-like)

经典布局(类Swagger风格)

csharp
options.WithClassicLayout();
csharp
options.WithClassicLayout();

Anti-patterns

反模式

Don't Expose Scalar in Production Without Auth

生产环境未加授权就暴露Scalar

csharp
// BAD — anyone can see your API structure
app.MapOpenApi();
app.MapScalarApiReference();

// GOOD — development only
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

// GOOD — production with auth
app.MapOpenApi().RequireAuthorization("ApiDocs");
app.MapScalarApiReference().RequireAuthorization("ApiDocs");
csharp
// 错误示例 —— 任何人都能查看你的API结构
app.MapOpenApi();
app.MapScalarApiReference();

// 正确示例 —— 仅在开发环境使用
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

// 正确示例 —— 生产环境带授权
app.MapOpenApi().RequireAuthorization("ApiDocs");
app.MapScalarApiReference().RequireAuthorization("ApiDocs");

Don't Pre-fill Real Credentials

预填充真实凭证

csharp
// BAD — real tokens visible in browser
options.AddHttpAuthentication("Bearer", auth =>
{
    auth.Token = "eyJhbG...real-production-token";
});

// GOOD — dev-only test tokens
if (app.Environment.IsDevelopment())
{
    options.AddHttpAuthentication("Bearer", auth =>
    {
        auth.Token = "dev-only-test-token";
    });
}
csharp
// 错误示例 —— 真实令牌会在浏览器中暴露
options.AddHttpAuthentication("Bearer", auth =>
{
    auth.Token = "eyJhbG...real-production-token";
});

// 正确示例 —— 仅使用开发环境测试令牌
if (app.Environment.IsDevelopment())
{
    options.AddHttpAuthentication("Bearer", auth =>
    {
        auth.Token = "dev-only-test-token";
    });
}

Don't Forget the Security Scheme Transformer

忘记配置安全方案转换器

csharp
// BAD — no auth UI in Scalar because OpenAPI doc has no security schemes
builder.Services.AddOpenApi();
app.MapScalarApiReference(options =>
{
    options.WithPreferredScheme("Bearer"); // Does nothing!
});

// GOOD — register the document transformer first
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
});
app.MapScalarApiReference(options =>
{
    options.WithPreferredScheme("Bearer");
});
csharp
// 错误示例 —— Scalar中无认证UI,因为OpenAPI文档未包含安全方案
builder.Services.AddOpenApi();
app.MapScalarApiReference(options =>
{
    options.WithPreferredScheme("Bearer"); // 无效!
});

// 正确示例 —— 先注册文档转换器
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
});
app.MapScalarApiReference(options =>
{
    options.WithPreferredScheme("Bearer");
});

Don't Leave the Proxy Enabled for Sensitive APIs

敏感API未禁用代理

csharp
// BAD — auth headers flow through proxy.scalar.com
app.MapScalarApiReference();

// GOOD — disable proxy for APIs with sensitive data
app.MapScalarApiReference(options =>
{
    options.WithProxy(null);
});
csharp
// 错误示例 —— 认证头会流经proxy.scalar.com
app.MapScalarApiReference();

// 正确示例 —— 为敏感API禁用代理
app.MapScalarApiReference(options =>
{
    options.WithProxy(null);
});

Don't Use Swagger UI for New .NET 10 Projects

新.NET 10项目仍使用Swagger UI

csharp
// BAD — Swashbuckle removed from templates, maintenance concerns
builder.Services.AddSwaggerGen();
app.UseSwaggerUI();

// GOOD — built-in OpenAPI + Scalar
builder.Services.AddOpenApi();
app.MapOpenApi();
app.MapScalarApiReference();
csharp
// 错误示例 —— Swashbuckle已从模板移除,存在维护隐患
builder.Services.AddSwaggerGen();
app.UseSwaggerUI();

// 正确示例 —— 使用内置OpenAPI + Scalar
builder.Services.AddOpenApi();
app.MapOpenApi();
app.MapScalarApiReference();

Decision Guide

决策指南

ScenarioRecommendation
API documentation UI
MapScalarApiReference()
with
MapOpenApi()
Development environmentDefault setup with
IsDevelopment()
guard
Production API docsAdd
.RequireAuthorization()
to both endpoints
Auth testing in dev
AddHttpAuthentication()
with test tokens
Dark theme preference
.ForceDarkMode()
or
.WithTheme(ScalarTheme.Moon)
Multiple API versionsMultiple
AddOpenApi()
calls — Scalar detects automatically
Sensitive APIs
.WithProxy(null)
to disable external proxy
Swagger-like layout
.WithClassicLayout()
Custom route
app.MapScalarApiReference("/api-docs")
场景推荐方案
API文档UI搭建配合
MapOpenApi()
使用
MapScalarApiReference()
开发环境默认配置,添加
IsDevelopment()
防护
生产环境API文档为两个端点都添加
.RequireAuthorization()
开发环境认证测试使用
AddHttpAuthentication()
配置测试令牌
偏好深色主题使用
.ForceDarkMode()
.WithTheme(ScalarTheme.Moon)
多API版本支持多次调用
AddOpenApi()
—— Scalar会自动识别
敏感API使用
.WithProxy(null)
禁用外部代理
类Swagger布局使用
.WithClassicLayout()
自定义路由使用
app.MapScalarApiReference("/api-docs")