[SOLVED] ASP.NET Core with SPA, how to handle invalid routes on root?

Issue

Our ASP.NET Core with Single Page App as client, is hosted on Azure Web Service. We noticed that all environments and deployment slots get an occasional POST action request on /index.html. In the ASP.NET Core application, http requests to the root is routed to the SPA application files through configuring the SPA static files provider middleware:

services.AddSpaStaticFiles(configuration => {
                configuration.RootPath = "ClientApp/dist/ClientApp";
});

When these POST actions are requested on /index.html, the application will throw an exception:

The SPA default page middleware could not return the default page ‘/index.html’ because it was not found, and no other middleware handled the request.

In turn, the exception causes issues in our performance monitoring as the exceptions are not caught/handled anywhere. Especially if this happens multiple times in a short time.

Question: What can we configure to either immediately return 403 or similar response, or setup such that we at least catch the exception?

Solution

I have found a solution in an issue case on GitHub. This solution will call on the middleware only when the request meets the correct condition: when it’s a GET request.

In the Configure method of the Startup class:

app.UseWhen(context => HttpMethods.IsGet(context.Request.Method), builder =>
{
    builder.UseSpa(spa =>
    {
       // ... add any option you intend to use for the Spa middleware
    });
});

Answered By – Superman.Lopez

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *