【问题标题】:How to read the variables from local.settings.json file in the constructor in Azure Function?如何从 Azure Function 的构造函数中的 local.settings.json 文件中读取变量?
【发布时间】:2022-01-04 08:35:22
【问题描述】:

我有下面的代码,我做了一些修改,现在我希望移动 local.settings.json 文件中的所有硬编码值。因此,应从 local.settings.json 文件中读取 baseurl、IAPID、base64account 等值。我怎样才能做到这一点?我尝试在 Json 文件中添加值,但它似乎只能在 Function 方法中读取,而不能在构造函数中读取。 所以基本上我的问题是如何清理这段代码?

namespace Model
{
    public class Function1
    {
   
    private readonly string baseURL;
    private readonly string IAPId;
    private readonly ServiceAccountCredential _saCredential;
    private TokenResponse _token;

    static readonly HttpClient client = new HttpClient();
    public Function1()
    {
      
      var  base64ServiceAccount = "xyzabc";           
      _iapId = "xyz.com";
      _saCredential = ServiceAccountCredential.FromServiceAccountData(new MemoryStream(System.Convert.FromBase64String(base64ServiceAccount)));
        client.DefaultRequestHeaders.Add("IMBuild", Environment.GetEnvironmentVariable("VERSION_HEADER") ?? "dev");
    }
   
    public async Task<HttpResponseMessage> ProxyRequest(Stream requestBody)
    {
        requestBody.Seek(0, SeekOrigin.Begin);            
        var token = await GetOauthToken();
        var url = "https://example.com";           
        HttpResponseMessage response = "POST" switch
        {
            "GET" => await client.GetAsync(url),
            "POST" => await client.PostAsync(url, ((Func<StreamContent>)(() =>
            {
                var content = new StreamContent(requestBody);
                content.Headers.Add("Content-Type", "application/json");
                return content;
            }))()),
            _ => throw new NotSupportedException($"Method POST is not supported"),
        };
        return response;
    }

    [FunctionName("Function1")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);          
        var req1 = await ProxyRequest(req.Body);
        string responseMessage = await req1.Content.ReadAsStringAsync();
        return new OkObjectResult(responseMessage);
    }

【问题讨论】:

    标签: c# azure-functions


    【解决方案1】:

    在构造函数中使用名为 IConfiguration Class 的依赖注入,如下所示:

    在使用IConfiguration注入的.Net 6(可能还有一些更早的版本)中,我们可以读取local.settings.json文件中定义的环境变量

    public Function1(IConfiguration configuration)
    {
        string setting = _configuration.GetValue<string>("MySetting");
    }
    
    

    MySetting 必须在local.settings.jsonValues 部分中:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "MySetting": "value"
      }
    }
    

    参考资料: Azure Functions with Configuration and Dependency Injection - PureSourceCode

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多