小编Mar*_*gić的帖子

如何在错误的API网址上返回404?(ASP.NET Core + SPA)

我需要在错误的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)

但这似乎是错误的,尽管它可以工作。

c# angular asp.net-core-2.1

6
推荐指数
1
解决办法
445
查看次数

标签 统计

angular ×1

asp.net-core-2.1 ×1

c# ×1