如何配置WebManifest支持深色模式与安装提示?

解读

国内面试官问“C# 如何配置 WebManifest 支持深色模式与安装提示”,并不是想听你背 HTML 规范,而是考察三点:

  1. 你是否知道 ASP.NET Core 作为 Web 服务端,如何“干净地”生成并托管 manifest.json;
  2. 你是否能把“深色模式”与“安装提示”这两个前端诉求,转换成后端可配置、可灰度、可运维的方案;
  3. 你是否理解 PWA 安装背后的生命周期,以及如何在 .NET 管道里拦截、统计、甚至推送自定义安装弹窗。

一句话:让你用 C# 思维解决“前端最后一公里”问题。

知识点

  1. Web App Manifest 规范:display、icons、theme_color、background_color、prefer_related_applications。
  2. 深色模式媒体查询与 manifest 的 color_scheme 适配策略。
  3. ASP.NET Core 静态文件中间件 & 缓存策略:StaticFileOptions、OnPrepareResponse、Cache-Control。
  4. 多环境配置:appsettings.{Environment}.json 与 IOptionsMonitor 热重载。
  5. PWA 安装触发条件:beforeinstallprompt、userGesture、ServiceWorker 更新。
  6. 自定义安装弹窗:中间件拦截 /install/prompt 路由,写 Cookie/Session 做去重,埋点统计。
  7. 图标自动化生成:利用 SkiaSharp 在发布阶段一次性裁切 192/512/1024 多分辨率图标,避免设计师反复输出。
  8. 安全与合规:国内小程序生态下,prefer_related_applications 跳转到微信小程序的 scheme 配置,以及工信部备案号在 manifest 中的隐藏字段。

答案

  1. 在 ASP.NET Core 项目根目录建立 Manifest 配置模型
public class PwaManifestOptions
{
    public string Name { get; set; }
    public string ShortName { get; set; }
    public string Description { get; set; }
    public string StartUrl { get; set; } = "/";
    public string Display { get; set; } = "standalone";
    public string ThemeColor { get; set; }
    public string BackgroundColor { get; set; }
    public List<Icon> Icons { get; set; } = new();
    public string[] Categories { get; set; } = Array.Empty<string>();
    public bool PreferRelatedApplications { get; set; }
    public List<RelatedApplication> RelatedApplications { get; set; } = new();
}
  1. 在 appsettings.Production.json 中给出深色与浅色两套主题
"PwaManifest": {
  "Name": "XX企业控制台",
  "ShortName": "XX控制台",
  "ThemeColor": "#1e1e1e",          // 深色主色
  "BackgroundColor": "#121212",
  "Icons": [
    { "src": "/icon-192-dark.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
    { "src": "/icon-512-dark.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
  ]
}

通过 IOptionsMonitor<PwaManifestOptions> 读取,支持运行时热重载,方便运营在晚上 8 点切到“深色皮肤”活动。

  1. 新建 ManifestController,路由 /manifest.json,动态序列化
[ApiController]
[Route("manifest.json")]
public class ManifestController : ControllerBase
{
    private readonly PwaManifestOptions _opt;
    public ManifestController(IOptionsSnapshot<PwaManifestOptions> opt) => _opt = opt.Value;

    [HttpGet]
    public IActionResult Get()
    {
        // 根据请求头 Sec-CH-Prefers-Color-Scheme 动态切换图标与主题色
        var prefersDark = Request.Headers["Sec-CH-Prefers-Color-Scheme"] == "dark";
        if (prefersDark)
        {
            _opt.ThemeColor = "#1e1e1e";
            _opt.BackgroundColor = "#121212";
            _opt.Icons.ForEach(i => i.Src = i.Src.Replace(".png", "-dark.png"));
        }
        return Ok(_opt); // System.Text.Json 自动序列化
    }
}

国内浏览器目前只有内核 110+ 支持该请求头,但提前布局可保兼容。

  1. 在 Startup.cs(或 Program.cs)把 manifest.json 纳入静态文件缓存策略,避免 CDN 边缘节点缓存旧主题
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        if (ctx.File.Name == "manifest.json")
        {
            ctx.Context.Response.Headers.CacheControl = "public,max-age=300"; // 5 分钟短缓存
        }
    }
});
  1. 安装提示中间件:拦截 /install/prompt,写 Session 标记已提示,防止刷新重复弹窗
app.Map("/install/prompt", async ctx =>
{
    var hasPrompt = await ctx.Session.GetStringAsync("pwa-prompt");
    if (hasPrompt != "true")
    {
        await ctx.Response.WriteAsJsonAsync(new { show = true });
        await ctx.Session.SetStringAsync("pwa-prompt", "true");
        // 此处可写日志或发 MQ,统计转化率
    }
    else
    {
        await ctx.Response.WriteAsJsonAsync(new { show = false });
    }
});

前端在 beforeinstallprompt 事件里先 fetch 该接口,根据返回决定是否弹自定义 UI,符合国内“用户必须点击”的交互合规要求。

  1. 最终 Razor 页面引用
<link rel="manifest" href="/manifest.json" crossorigin="use-credentials">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1e1e1e">
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff">

至此,深色模式与安装提示全部受 ASP.NET Core 配置中心管控,一次编译,多环境灰度。

拓展思考

  1. 如果企业同时运营微信小商店与独立 PWA,如何在 manifest 里声明 prefer_related_applications,并在用户点击“安装”时优先拉起微信小程序?需要后端提供动态 scheme(weixin://dl/business/?t=XXXX),并做 A/B 测试统计拉起率。
  2. 国内厂商 ROM 对 PWA 安装弹窗有二次拦截,如何利用 ServiceWorker 的 updatefound 事件,在检测到新版本时提示用户“刷新升级”,从而变相提升留存?
  3. 当企业客户要求“图标必须带节日角标”时,如何用 SkiaSharp 在 CI 阶段自动合并角标图层,并同步更新 manifest 中的 src 路径,避免手工发布?
  4. 在微服务场景下,将 manifest.json 下沉到 BFF(Backend for Frontend)层,由聚合服务根据用户标签返回不同的 theme_color 和图标,实现“千人千面”的 PWA 皮肤,如何做配置版本号对齐与回滚?

把这些问题想透,面试时就能从“会配 manifest”跃迁到“能用 C# 做企业级 PWA 运营平台”。