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);
}