访问.NET 5 Azure Functions中的FunctionAppDirectory

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

我需要访问 Azure Functions 中的

FunctionAppDirectory

这是该函数的简化版本

[Function("Test")]
public static HttpResponseData Test([HttpTrigger(AuthorizationLevel.Function, "post", Route = "Test")] HttpRequestData req, 
ExecutionContext context, FunctionContext fContext)
{
    var log = fContext.GetLogger(nameof(TestOperations));
    log.LogInformation(context?.FunctionAppDirectory?.ToString());
    return req.CreateResponse(HttpStatusCode.OK);
}

ExecutionContext
此处为空。

我的Program.cs文件

class Program
{
    static Task Main(string[] args)
    {
        var host = new HostBuilder()
            .ConfigureAppConfiguration(configurationBuilder =>
            {
                configurationBuilder.AddCommandLine(args);
            })
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureServices(services =>
            {
                // Add Logging
                services.AddLogging();
            })
            .Build();

        return host.RunAsync();
    }
}

在 .NET 5 中运行的 Azure 函数

如何配置 ExecutionContext 的绑定或以其他方式获取 FunctionAppDirectory?

azure azure-functions .net-5
2个回答
6
投票

正如 Alex 在评论中提到的,azure function .net 5 现在不支持“context.FunctionAppDirectory”来获取函数应用程序的目录。

在函数应用3.0中,“ExecutionContext”被设计在“Microsoft.Azure.WebJobs”包中。但在您的代码中,ExecutionContext 来自“System.Threading”。所以这些是不同的类。

您可以使用以下代码获取.NET 5.0 azure function中的azure function目录:

using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace FunctionApp6
{
    public static class Function1
    {
        [Function("Function1")]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("Function1");
            logger.LogInformation("C# HTTP trigger function processed a request.");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            var local_root = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
            var azure_root = $"{Environment.GetEnvironmentVariable("HOME")}/site/wwwroot";
            var actual_root = local_root ?? azure_root;

            response.WriteString(actual_root);

            return response;
        }
    }
}

0
投票

对我来说,这很有效:

var rootDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
© www.soinside.com 2019 - 2024. All rights reserved.