How to return an error on an invalid api request, using ASP.Net Core 3, SPA app

1k Views Asked by At

I am using a SPA (React) app in ASP.Net Core 3.

What is happening is any request will first go to the back end and allow .Net to try and route it, if no route is found, it returns index.html and assumes that the SPA can handle routing.

Most the time I am quite happy with this, but I want to know if there is a way of excluding any routers to api/ in that.

I find it very annoying that index.html is returned (with a 200) on any made-up api/MadeUp/Request. Can't I have it returning 500 on invalid api requests, but still allowing the SPA to manage any other requests (i.e. returning index.html)?

1

There are 1 best solutions below

1
On BEST ANSWER

You can add a middleware between UseEndpoint() and UseSpa() and return a 404 (or 500 if you prefer) if request uri starts with /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");
    }
});