I have encountered an unusual gotcha situation with **ASP.NET Core'**s error handling while working on a web API lately. The API worked correctly during development, but when deployed to Azure, our endpoints started returning HTTP 404 Not Found errors. The situation was even more curious, as when we posted invalid data, the model validation in our action methods correctly returned a HTTP 400 Bad Request. Confusingly, the 404 errors occurred only with valid input data. We utilized diagnostic logging in Azure App Service to see what is going on behind the scenes to discover that in fact the connection string to our SQL database was invalid and SqlException
was thrown during any attempt to use it. That explained why valid requests failed, but we definitely didn't see why we are getting a 404 error instead a 500 (Internal Server Error). I figured the problem must be hidden somewhere in the request pipeline, so I peeked into the Startup.cs
file's Configure
method. And indeed, there was our culprit!
Because our application was based on the MVC template it contained an redirect to exception handling route with the UseExceptionHandler
middleware. Unfortunately for us, this route was not implemented, as we worked solely on the API. When an unhandled exception happened during our request, it bubbled up to the exception handler middleware, which attempted to handle it with the /Error
route. This route was nowhere to be found, hence our 404 error was born. The takeaway of this gotcha experience is to always make sure all possible paths of the request pipeline are configured properly.