如何使用 ASP.Net Core 3、SPA 应用程序返回无效 api 请求的错误

Jon*_*eel 3 asp.net-web-api asp.net-spa asp.net-core

我在 ASP.Net Core 3 中使用 SPA (React) 应用程序。

正在发生的是任何请求将首先进入后端并允许 .Net 尝试路由它,如果没有找到路由,它会返回index.html并假设 SPA 可以处理路由。

大多数时候我对此很满意,但我想知道是否有办法排除任何路由器api/

我觉得很烦人,在任何虚构的 .html 上返回 index.html(带有 200)api/MadeUp/Request。我不能让它在无效的 api 请求上返回 500,但仍然允许 SPA 管理任何其他请求(即返回 index.html)?

Kah*_*azi 9

您可以之间添加一个中间件UseEndpoint()UseSpa()并返回一个404(或500,如果你喜欢)如果请求的URI开头/api

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});

app.Use((context, next) =>
{
    if(context.Request.Path.StartsWithSegments(new PathString("api")))
    {
        context.Response.StatusCode = StatusCodes.Status404NotFound;
        return Task.CompletedTask;
    }

    return next();
});

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});
Run Code Online (Sandbox Code Playgroud)