从 spa 文件夹提供静态 index.html

Serving static index.html from the spa folder

我使用 .netcore 服务器端和 vuejs 2.

我已经为我的 vuejs 的一些路由生成了 html 文件,我直接放在 dist 文件夹中:

我可以使用 http://my-domain/en/home/index.html 访问 html 文件,但调用 http://my-domain/en/home(没有 index.html)将无法提供 html 文件。相反,它将 return 等效的水疗页面。

我该怎么做才能解决这个问题?我希望服务器优先 return html 文件,否则 return 普通水疗网站。

这是我的一部分 startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // ...

    // In production, the vue files will be served from this directory
    services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });

    // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    // WebRootPath == null workaround. - from https://github.com/aspnet/Mvc/issues/6688
    if (string.IsNullOrWhiteSpace(env.WebRootPath))
    {
        env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "ClientApp", "dist");
    }

    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            const int durationInSeconds = 60 * 60 * 24;
            ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
        }
    });
    app.UseSpaStaticFiles();

    // ...

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

        if (env.IsDevelopment())
        {
            spa.UseVueCli(npmScript: "serve", port: 8085);
        }
    });
}

编辑:在@Phil 的回复之上,我需要提供一个 FileProvider,因为 UseDefaultFiles 没有在正确的文件夹中查找:

app.UseDefaultFiles(new DefaultFilesOptions
{
    FileProvider = new PhysicalFileProvider(env.WebRootPath) // important or it doesn't know where to look for
});

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        const int durationInSeconds = 60 * 60 * 24;
        ctx.Context.Response.Headers[HeaderNames.CacheControl] =
            "public,max-age=" + durationInSeconds;
    },
    FileProvider = new PhysicalFileProvider(env.WebRootPath) // same as UseDefaultFiles
});

你需要告诉服务器使用Default Files

With UseDefaultFiles, requests to a folder search for:

default.htm
default.html
index.htm
index.html

app.UseDefaultFiles(); // this must come first
app.UseStaticFiles(...

这基本上是为文件夹(如您的 en/home)上的请求设置一个拦截器,如果它找到上述任何文件名,就会将 URL 重写为 folder/path/{FoundFilename}

如果您想避免搜索 index.html 以外的任何内容,您可以对其进行自定义

DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(options);

注意关于订购的重要信息

Important

UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL rewriter that doesn't actually serve the file. Enable Static File Middleware via UseStaticFiles to serve the file.