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

拥有回忆 提交于 2021-02-20 15:33:34

问题


I have an ASP.NET Core 2.1 app that I've hosted in an Azure app service. When executed locally I'm able to access the controller. But when I host in an Azure app I receive a 404. Here are the minimal steps to reproduce.

In Visual Studio 2017 add a new project. Select ASP.NET Core Web Application. Select ASP.NET Core 2.1, API project template, no authentication, configure for HTTPS. Run the new app as a self hosted (not using IIS). Browse to https://localhost:5001/api/values. I get the expected response (although there is an exception on the command line about failure to authenticate HTTPS connection).

Right click the project and select publish. Select to create a new app service. I selected my existing subscription, hosting plan, and resource group. I left the default app name. Create the app.

Browse to the url https://app_name.azurewebsites.net and I see the default page. Browse to https://appname.azurewebsites.net/api/values and I get a 404.

I'm sure I'm missing something quite stupid, but I just can't figure it out.


回答1:


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
{

}



回答2:


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())
   ...
else
{
    app.UseExceptionHandler("/Home/Error"); << Watch for this
    ...
}


来源:https://stackoverflow.com/questions/55658948/asp-net-core-api-get-404-on-azure-app-service-but-works-ok-on-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!