0

I have below code and I did some modification and now I am looking to move all the hardcoded values in local.settings.json file. So values like baseurl, IAPID , base64account should be read from local.settings.json file. How can i do that? I tried adding the values in Json file but it seems to be readable only inside Function method and not in the constructor. So basically my question is how can I clean this code?

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);
    }
ZZZSharePoint
  • 1,163
  • 1
  • 19
  • 54

1 Answers1

2

Use dependency Injection called IConfiguration Class in the constructor like below:

enter image description here

In .Net 6(and probably some earlier versions) using IConfiguration injection, we can read the environment variables defined in the local.settings.json file

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

MySetting must be in the Values section of local.settings.json:

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

References: Azure Functions with Configuration and Dependency Injection - PureSourceCode