ASP.NET Core API-在Azure App Service上获取404,但在Localhost上可以正常运行 [英] ASP.NET Core API - Get 404 on Azure App Service, but works ok on Localhost

查看:50
本文介绍了ASP.NET Core API-在Azure App Service上获取404,但在Localhost上可以正常运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Azure应用服务中托管的ASP.NET Core 2.1应用.在本地执行时,我可以访问控制器.但是,当我在Azure应用程序中托管时,我会收到404.这是重现的最少步骤.

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.

在Visual Studio 2017中添加一个新项目.选择"ASP.NET Core Web应用程序".选择ASP.NET Core 2.1,API项目模板,不进行身份验证,为HTTPS配置.以自托管的方式运行新应用(不使用IIS).浏览至https://localhost:5001/api/values.我得到了预期的响应(尽管命令行上有一个关于无法验证HTTPS连接的异常).

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.

浏览到URL https://app_name.azurewebsites.net ,我看到了默认页面.浏览到 https://appname.azurewebsites.net/api/values ,我得到一个404

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.

推荐答案

我能够重现该错误,以下解决方案为我工作.如果您以前没有尝试过,请尝试一下.

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

  1. 在将应用程序发布到Azure之前,请确保将配置设置为发布模式".
  2. 在ValuesController中的GET方法顶部添加 [Route("/")] 属性,如下所示.

[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.

使用[Route]属性时,将定义属性路由,因此该操作/控制器不使用常规路由.

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

作为一种选择,您可以使用以下事实:属性路由可以与继承结合在一起.在整个控制器上设置一个Route属性,它将用作路由前缀(与WebApi中的[RoutePrefix]属性相同的行为):

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
{

}

这篇关于ASP.NET Core API-在Azure App Service上获取404,但在Localhost上可以正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆