我需要在错误的api调用上返回404,以便可以在客户端(角度5)上为用户创建正确的响应。当前后端返回状态码200和index.html,这导致前端json解析错误。
我使用ASP.NET Core 2.1和Angular模板项目创建了新的Web项目。这是该模板发布版本的链接。我根本没有更改模板代码,我只是将其发布在azure上。(在开发模式下,我收到404错误,如预期)。
如此处所述,默认行为应为404。
这里是Startup.cs,这里 SampleDataController.cs。
我想到在中使用这样的东西Startup.cs:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}");
});
app.MapWhen(x => x.Request.Path.Value.Contains("/api"), builder =>
{
builder.UseMvc(routes =>
{
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Error" });
});
});
Run Code Online (Sandbox Code Playgroud)
在HomeController.cs:
public IActionResult Error()
{
return NotFound();
}
Run Code Online (Sandbox Code Playgroud)
但这似乎是错误的,尽管它可以工作。