How to produce correct error for Blazor MapFallbackToFile()(如何为Blazor MapFallback ToFile()生成正确的错误)
问题描述
我有一个既想用作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
错误。
这篇关于如何为Blazor MapFallback ToFile()生成正确的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为Blazor MapFallback ToFile()生成正确的错误


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01