我创建了一个新的azure函数,并且我有一个读取host.json的步骤,它在我的办公 table 上运行,但是当我发布到Azure时,我收到错误:
The configuration file 'host.json' was not found and is not optional. The physical path is 'D:\Program Files (x86)\SiteExtensions\Functions\2.0.12507\32bit\host.json'.
这是我尝试过的:
var Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("host.json",false)
.Build();
var value = Configuration["value"];
那么我该如何解决这个问题呢?
最佳答案
正如 Volodymyr 提到的,您需要在 Azure Function 方法中传递 ExecutionContext:。
public static async Task<IActionResult> Run( ... , ExecutionContext context)
{
...
}
现在,当您构建配置时,您可以使用 ExecutionContext.FunctionAppDirectory
属性设置基本路径。我还可以选择添加 local.settings.json 以进行本地调试:
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory) // Here you include the app directory from the context
.AddJsonFile("host.json", optional: false, reloadOnChange: true)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) // for local debugging
.AddEnvironmentVariables()
.Build();
<小时/>
为了进一步改进您的代码,我建议为您的设置创建一个类。例如:
public sealed class FunctionSettings
{
public string MySetting { get; set; }
}
这样您就可以访问如下设置:
var settings = new FunctionSettings();
config.Bind(settings);
var value = settings.MySetting
而不是
var value = Configuration["MySetting"];
关于azure - 找不到主机.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56625082/