ASP.NET Core API - Get 404 on Azure App Service, but works ok on Localhost

One possible cause of differing behaviour is the standard if (env.IsDevelopment()) branch in Startup.cs -> Configure(), which will change depending on the value of the ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT env vars. These will default to production

In my case, I had removed the Home controller entirely, but inadvertently left the app.UseExceptionHandler middleware in Startup.Configure pointed at the default Home/Error.

So when my app was deployed to Azure, an exception happened which I didn't receive during local testing (e.g. SQL Firewall IP blocking issue), and this meant that any redirection to the error page resulted in a 404.

if (env.IsDevelopment())
   ... << Local environment (ASPNETCORE_ENVIRONMENT = 'Development')
else
{
    app.UseExceptionHandler("/Home/Error"); << Watch for this
    ...
}

I was able to reproduce the error and below solution worked for me. Try this if you haven't tried earlier.

  1. Ensure the configuration is set to Release Mode before publishing the app to Azure.
  2. Add [Route("/")] attribute on top of your GET method in ValuesController like below.

    [Route("/")]
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return "value";
    }
    

Basically, Any controller methods that do not have a route attribute use convention-based routing.

When you use [Route] attribute, you define attribute routing and so conventional routing is not used for that action/controller.

As an option, you can use the fact, that attribute routes can be combined with inheritance. Set a Route attribute on the entire controller and this will work as route prefix (the same behavior as [RoutePrefix] attribute in WebApi):

[Route("api/[controller]")]
public class ValuesController: ControllerBase
{

}