首页 > 解决方案 > ASP.NET Core UseFileServer 并在 404 上重定向

问题描述

我正在使用以下代码将 SPA 嵌入到 C# 库中,以便在 ASP.NET Core 应用程序中使用。

public static IApplicationBuilder UseSharedUI(this IApplicationBuilder app)
{
    app.UseFileServer(new FileServerOptions
    {
        RequestPath = "/shared-ui",
        FileProvider = new ManifestEmbeddedFileProvider(assembly: Assembly.GetAssembly(typeof(Builder)), "UI/dist"),
    });

    return app;
}

这有效,当我运行 API 时,我可以访问/shared-ui路由下的 SPA。但是当我在浏览器中的路由中进行刷新时/shared-ui/analytics,我收到 404 错误,因为应用程序不知道如何处理子路由,它应该回退到 SPA 来处理它。

我尝试添加以下代码,但行为是相同的。

    app.MapWhen((context) => context.Request.Path.StartsWithSegments("/shared-ui"), (appBuilder) =>
    {
        app.UseStaticFiles();
        appBuilder.UseRouting();
        appBuilder.UseEndpoints(endpoints =>
        {
            endpoints.MapFallbackToFile("/shared-ui/index.html");
        });
    });

有什么办法可以做到这一点?

标签: c#asp.net-core.net-core

解决方案


推荐阅读