c# - Azure Function(使用 DI)无法删除 "/api"路由前缀

标签 c# azure dependency-injection azure-functions

所以我知道这两个问题似乎在问同一件事:

How to remove the word ‘api’ from Azure functions url

How to change the base "/api" path on Azure Functions (v2)?

但是,我仍然无法摆脱路由中的“api”前缀。

我的 host.json 看起来像:

{
  "version": "2.0",
  "extensions": {
    "http": {
      "routePrefix": ""
    }
  }
}

在我的 HttpTrigger 上,我正在设置自定义路由:

[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "myapp")] HttpRequest request,

但是,当我在本地运行应用程序时,终点出现为:

[POST] http://localhost:7071/api/myapp

如果我将 host.json 更改为:

{
  "version": "2.0",
  "extensions": {
    "http": {
      "routePrefix": "something"
    }
  }
}

我的应用程序现在正在运行:

[POST] http://localhost:7071/something/myapp

因此,给出空字符串 "" 似乎不起作用。有任何想法吗? (我已经完成了所有常规操作:清理解决方案、删除 bin/obj 文件夹等)

仅供引用,我正在使用的函数应用程序:

<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.7" />

编辑:

我还从函数应用程序引用这些包(尽管我不知道这会如何导致此问题):

<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.1" />

编辑2

我已将问题范围缩小到在 Startup.cs 中调用的这段代码:

IConfiguration configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();

IConfiguration combinedConfig = new ConfigurationBuilder()
    .AddConfiguration(configuration)
    .AddAzureKeyVault(kvEndpoint, kvClient, new DefaultKeyVaultSecretManager());
    .Build();

builder.Services.AddSingleton(combinedConfig);
// <-- this line causes the prefix "" to revert to "/api"

它本质上是将 key 保管库作为配置提供程序添加到已准备好的提供程序堆栈中。 (请注意,我在配置生成器上调用什么 .Add 方法并不重要,它的注册导致了问题)。也许还有另一种写法吗?

最佳答案

所以看来我犯的错误很小。在下面的代码中:

IConfiguration configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();

IConfiguration combinedConfig = new ConfigurationBuilder()
    .AddConfiguration(configuration)
    .AddAzureKeyVault(kvEndpoint, kvClient, new DefaultKeyVaultSecretManager());
    .Build();

builder.Services.AddSingleton(combinedConfig);

ConfigurationBuild.Build() 实际上返回一个 IConfigurationRoot,而不是 IConfiguration(IConfigurationRootIConfiguration)。因此,当注册它时,我丢失了一些东西(可能是配置提供程序信息)。

简单地改变:

IConfiguration combinedConfig

IConfigurationRoot combinedConfig

解决了问题(或者您可以使用var,我可能应该使用它!)。

虽然这解决了问题,但我仍然有点困惑为什么在将 host.json 中的 routePrefix 更改为某些非空字符串之前可以工作,但将其设置为空字符串才不是。本来以为只要在 host.json 中进行设置就可以应用该值,而没有它则意味着恢复为默认的“api”

关于c# - Azure Function(使用 DI)无法删除 "/api"路由前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62442179/

相关文章:

c# - 在c#中使用字符串数据类型列表创建元组

azure - 使用 Azure 或 App Studio 将 Bot 部署到 MS Teams?

android - 如何使用 Visual Studio 将 Android 设备连接到 Azure VM

azure - 如何停止为 Azure Web App 运行多个应用程序见解?

java - Spring - Bean 没有被注入(inject)

c# - 依赖注入(inject)抽象库

c# - 谁能一眼就告诉我为什么这个 Action 这么慢?

c# - 当我需要编辑的版本时,DataGrid.ItemsSource 返回旧数据

c# - 通过 LINQ 创建 XML 文档,添加 xmlns,xmlns :xsi to it

c# - 重构时机成熟——.NET 依赖注入(inject)