首页 > 解决方案 > ASP.NET Core - 为 SPA 提供不同的 HTML 文件?

问题描述

问题

如何在 ASP.NET Core 中为 SPA 应用程序 (Vue) 提供不同的 HTML(条目)文件?

解释

根据条件,我想提供不同的 HTML 页面(就像控制器为非 SPA 所做的那样)。该页面仍将包含 Vue 应用程序的入口点<div id="app">,但应在提供 HTML 之前进行一些其他更改。

我知道我必须以某种方式更改 startup.cs 文件,因为它会呈现 HTMLapp.UseStaticFiles()app.UseSPAStaticFiles()

例子

条件 1满足,base.htmlclient -> public -> base.html

相反,条件 2special.html得到满足,从client -> public -> special.html

代码

基本的 HTML 看起来像这样:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <title>Title</title>
</head>

<body>
  <noscript>
    <strong>We're sorry but this webpage doesn't work properly without JavaScript enabled. Please enable it to
      continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
</body>

</html>

startup.cs 的重要部分如下所示:

services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/dist";
});

// ....

app.UseStaticFiles();
app.UseSpaStaticFiles();

// ....

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");

    if (env.IsDevelopment())
    {
        endpoints.MapToVueCliProxy(
            "{*path}",
            new SpaOptions { SourcePath = "ClientApp" },
            npmScript: "serve",
            regex: "Compiled successfully");
    }

    // Add MapRazorPages if the app uses Razor Pages. Since Endpoint Routing includes support for many frameworks, adding Razor Pages is now opt -in.
    endpoints.MapRazorPages();
});

// ....

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
});

标签: htmlasp.netvue.jsasp.net-coresingle-page-application

解决方案


推荐阅读