ASP.NET Core 8:对于 /api 之外的每个 POST 操作都返回 404

问题描述 投票:0回答:1

当前情况:我在 /api/* 下运行一些控制器,在 /en/* 下运行 SPA

一些蹩脚的爬虫或机器人会发出一些无效的 POST 调用,例如不存在的 /en/index.php。

这会导致如下异常:

An unhandled exception has occurred while executing the request.                                                                                                                           
      System.InvalidOperationException: The SPA default page middleware could not return the default page '/en/index.html' because it was not found, and no other middleware handled the request.

是否可以对 /api 未处理的每个后期操作返回干净的 404?

asp.net
1个回答
0
投票

我找到了答案:

WebApplication app = builder.Build();
app.Use(async (context, next) =>
{
    string path = context.Request.Path.Value ?? string.Empty;
    if (context.Request.Method.Equals(HttpMethods.Post, StringComparison.InvariantCultureIgnoreCase) && !path.StartsWith("/api"))
    {
        context.Response.StatusCode = 404;
        await context.Response.WriteAsync("Not Found");
        return;
    }
    await next(context);
});

它检查请求是否是 POST 并且不是以 /api 开头,然后返回 404。

它可以工作,但欢迎优化!

© www.soinside.com 2019 - 2024. All rights reserved.