如何将端点映射到 ASP 中的静态文件。NET 核心?

she*_*rtu 7 c# asp.net routes asp.net-core

我正在 ASP .NET Core 中构建一个单页 Web 应用程序,这需要我将一些 URL 映射到一个端点,该端点为名为“index.html”的特定静态文件提供服务。

目前,我使用了一种 hack 解决方案,将所有URL 映射到端点。

_ = app.UseEndpoints(endpoints => {
    _ = endpoints.MapControllers();

    _ = endpoints.MapGet("/test", async context => {
        // I need some way to serve the static file in the response
        await context.Response.WriteAsync("Hello world");
    });

    // TODO replace with actual endpoint mapping
    //_ = endpoints.MapFallbackToFile("index.html");
});
Run Code Online (Sandbox Code Playgroud)

相反,我只想将一组特定的 URL 映射到端点。我该如何实现这个目标?

she*_*rtu 1

解决方案是实现 URL 重写,将 URL 重写为 index.html,并为“/”根 URL 添加使用默认文件。

RewriteOptions rewriteOptions = new RewriteOptions()
                .AddRewrite("test", "index.html", true);

_ = app.UseRewriter(rewriteOptions);

_ = app.UseDefaultFiles();
Run Code Online (Sandbox Code Playgroud)

此部分代码位于UseRouting 中间件调用之前。