如何为Blazor MapFallback ToFile()生成正确的错误

人气:881 发布:2022-10-16 标签: c# asp.net-core-webapi blazor-webassembly

问题描述

我有一个既想用作Web API又想用作Blazor wasm UI的项目。此API还将从其他项目访问,因此我希望该API向使用者提供有用的错误详细信息。

我现在让站点使用MapFallbackToFile()方法同时达到这两个目的,但是,如果您尝试对仅接受GET的终结点执行POST,则会得到404响应,而不是无效http方法的405

我使用的是this question中提供的解决方案,以便仅映射非API路径,但这始终是404,我担心它会隐藏请求的任何其他潜在问题。

如何才能使HandleApiFallback()方法简单地像Web API通常那样工作,同时仍然从提供Blazor页面的服务中排除/api/路径?


app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.Map("api/{**slug}", HandleApiFallback);
    endpoints.MapFallbackToFile("{**slug}", "index.html");
});

private Task HandleApiFallback(HttpContext context)
{
    context.Response.StatusCode = StatusCodes.Status404NotFound;
    return Task.CompletedTask;
}

集成测试示例:

    var response = client.GetAsync(path).GetAwaiter().GetResult();
    response.StatusCode.Should().Be(HttpStatusCode.OK);

    var response2 = client.PostAsJsonAsync(path, "").GetAwaiter().GetResult();
    response2.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed);

当您使用任何MapFallbackToFile()时,第二个断言作为404而不是405失败。

推荐答案

我通过查看一个案例找到了一个解决方案,其中您可能需要在不同的设备上运行多个Blazor应用程序,并对其进行了修改以适应我的使用案例:


//explicitly only use blazor when the path doesn't start with api
app.MapWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api"), blazor =>
{
    blazor.UseBlazorFrameworkFiles();
    blazor.UseStaticFiles();

    blazor.UseRouting();
    blazor.UseEndpoints(endpoints =>
    {
        endpoints.MapFallbackToFile("index.html");
    });
});

//explicitly map api endpoints only when path starts with api
app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), api =>
{
    //if you are not using a blazor app, you can move these files out of this closure
    api.UseStaticFiles();
    api.UseRouting();
    api.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
    });
});

这通过了我提到的集成测试,因此当我尝试对API而不是404使用错误的HTTP方法时,我会得到正确的405错误。

228