未找到 Azure 函数文件

Azure function file not found

我创建了一个 Azure 函数,它使用需要属性文件才能工作的包。从他们实现这个的方式来看,我需要将 属性 文件位置传递给包。

ConfigFactory.setConfigLocation("SomeFolder/AnotherFolder/connector.properties");

当我 运行 在本地运行时,一切正常,一切正常。但是,当我在 Azure 上发布它时,它告诉我文件 url 无效,

[Error] Invalid url to location ]SomeFolder/AnotherFolder/connector.properties[ errorMessage :no protocol: SomeFolder/AnotherFolder/connector.properties file

我错过了什么吗?为什么这不仅仅适用于 Azure?

在 azure 函数中引用文件你有 2 个选项。

使用执行上下文

[FunctionName("MyNewHTTPAzureFunction")]

public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;
    string responseMessage = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." : $"Hello, {name}. This HTTP triggered function executed successfully.";
    
    //This is how you can access the curent Directory with the help of context.FunctionAppDirectory
    
    string localFile = Path.Combine(context.FunctionAppDirectory, "Data", "Your_file_with_extension");   
    string readLocalFile = File.ReadAllText(localFile);
    
    ...... // your business needs
    
    return new OkObjectResult(responseMessage);
}

使用Path.GetDirectoryName:

如果您无权访问 ExecutionContext,则访问 Azure Function 的目录。

您可以在 Startup class 中读取本地文件,如下所示。

var getPath= Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

var rootpath = Path.GetFullPath(Path.Combine(binpath, ".."));

///Read the file

File.ReadAllText(rootpath + "/path/to/filename_with_extension");

Azure 函数访问路径被拒绝

为了避免 Azure 函数中的访问被拒绝错误,您始终尝试将文件保存在 D:\home\site\wwwroot (根目录) 目录中Azure 函数驻留。

参考更多信息here & Doc for Binding Expression pattern