Blazor WASM 路由发布请求到 index.html

Posted

技术标签:

【中文标题】Blazor WASM 路由发布请求到 index.html【英文标题】:Blazor WASM Route Post Request to index.html 【发布时间】:2021-12-06 22:38:00 【问题描述】:

我有一个使用 Visual Studio 模板设置的 Blazor WASM 应用。我在 Server 项目的 Startup.cs 文件中的路由如下所示:

app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>

    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("index.html",);
);

每当我向我没有控制器的路由发出 GET 请求时,它一直工作得很好,并从我的客户端项目中提供 wwwroot/index.html 文件。客户端项目中的 Blazor 框架将其用于那里。但是,我现在需要支持将 index.html 文件从 GET 或 POST 请求返回到我的应用程序中没有控制器的端点。我很难弄清楚如何设置它。我已经尝试了EndpointRouteBuilderExtensions.MapPost 方法并且能够返回字符串,但没有看到任何使用它返回文件的好例子。这不起作用:

endpoints.MapPost("*", (HttpContext context) => 
    context.Request.Path = "/index.html";
    context.SetEndpoint(null);
);

虽然它类似于框架方法 StaticFilesEndpointRouteBuilderExtensions.MapFallbackToFile 所做的:https://github.com/dotnet/aspnetcore/blob/fc4e391aa58a9fa67fdc3a96da6cfcadd0648b17/src/Middleware/StaticFiles/src/StaticFilesEndpointRouteBuilderExtensions.cs#L194

我的问题与此类似:How do I map an endpoint to a static file in ASP. NET Core? 但那里的答案不适用于我的情况。

【问题讨论】:

嗨@Chris,您确定使用 blazor WASM 而不是 blazor 服务器应用程序吗? @Rena,是的,我很确定这是一个 WASM 应用程序。 WASM 和 Web API 部分部署到同一台服务器,Web API 代码处理路由请求/为 WASM 应用程序提供 index.html。 【参考方案1】:

我有一种方法可以帮助你。您可以告诉网络服务器将它找不到的任何路由路由到您的 index.html。 nginx 中的语法是

try_files $uri $uri/ /index.html =404;

不确定这是否能解决您的问题,因为我尚未使用 Wasm 中的 Api 控制器对此进行测试。

【讨论】:

【参考方案2】:

在阅读了更多的 aspnetcore 源代码和 MapFallbackToFile 之后,我想出了适合我的解决方案。我的服务器解决方案的 Startup.Configure 方法是这样的:

app.UseEndpoints(endpoints =>

    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapPost("*path:nonfile", CreatePostIndexRequestDelegate(endpoints));
    endpoints.MapFallbackToFile("index.html");
);

我在 Startup 类中添加了这个新方法:

//This method allows Post requests to non-file, non-api endpoints to return the index.html file
private static RequestDelegate CreatePostIndexRequestDelegate(IEndpointRouteBuilder endpoints)

    var app = endpoints.CreateApplicationBuilder();
    app.Use(next => context =>
    
        context.Request.Path = "/index.html";
        context.Request.Method = "GET";
        // Set endpoint to null so the static files middleware will handle the request.
        context.SetEndpoint(null);
        return next(context);
    );
    app.UseStaticFiles();
    return app.Build();

【讨论】:

以上是关于Blazor WASM 路由发布请求到 index.html的主要内容,如果未能解决你的问题,请参考以下文章