Azure Web 应用程序 - API 路由在发布到 Azure 后不起作用

问题描述 投票:0回答:1

我在 Azure 上有一个 .NET 7 的 Web 应用程序。

我已经像这样配置了路由:

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "weka",
                pattern: "weka/{controller}/{action}/{code?}",
                defaults: new { controller = "WEKA", action = "GetWekaProvoz" }
            );
        });

我有这样的控制器:

  [Route("weka")]
  [ApiController]
  public class WEKAController : ControllerBase
  {

      [HttpGet("provoz/{code}")]
      public IActionResult GetWekaProvoz(string code)
      {
          result = GetSQLWekaProvoz(code.ToUpper());    
          if (result == null || result== string.Empty)
          {
              return new NotFound();
          }

          return new OkObjectResult(result); //Returns JSON
      }

在本地 IIS Express 上,此路由运行良好,并转到适当的控制器并返回 JSON:

https://localhost:44354/weka/provoz/CODE

发布后在 Azure 上我仅获得默认应用程序,路由不起作用:

https://myapp.azurewebsites.net/weka/provoz/CODE

可能是什么问题?

c# azure .net-7.0 azure-webapps asp.net-routing
1个回答
0
投票

问题可能出在

pattern
方法中的
MapControllerRoute
属性。当您将应用程序发布到 Azure 时,URL 模式的解释方式与本地计算机上的不同。

  • Azure 使用

    ~
    字符来表示应用程序的基本 URL,因此您需要在模式前面添加
    ~

  • 将 ASP .NET Core 应用程序发布到 Azure 应用服务时,会为该应用程序分配一个基本 URL。此基本 URL 用于为应用程序的所有 URL 添加前缀。例如,如果您的应用程序部署到

    https://<your-app-name>.azurewebsites.net
    URL,则应用程序的所有 URL 都将以该基本 URL 开头。

  • 在 ASP .NET Core 应用程序中配置路由时,可以使用

    pattern
    属性来指定应用程序应匹配的 URL 模式。但是,当您将应用程序发布到 Azure 时,您需要在
    pattern
    属性前面添加
    ~
    字符。

  • 这告诉 ASP .NET Core 应相对于应用程序的基本 URL 来解释 URL 模式。

例如,以下路由配置将在您的本地计算机上运行:

endpoints.MapControllerRoute(
    name: "default",
    pattern: "Home/Index"
);

但是,当您将应用程序发布到 Azure 时,您需要在

pattern
属性前面添加
~
字符:

endpoints.MapControllerRoute(
    name: "default",
    pattern: "~/Home/Index"
);

所以我添加了一个控制器并尝试使用以下模式

app.MapControllerRoute(
    name: "products",
    pattern: "~/products/{action=List}/{id?}",
    defaults: new { controller = "Product" });

结果 路由至所需路线 本地 enter image description here

部署到应用服务 enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.