I set my function timeout for my Azure Function App in the host.json
on deployment:
{
"version": "2.0",
"functionTimeout": "00:10:00", //max 10 minutes
...
}
But how I can I access the value (read it) from within my C# function code. This isn't an environment variable, is it?
CodePudding user response:
Code to get host.json variables:
string jsonfile = "host.json";
string jsonText = GetFileJson(jsonfile);
JObject jsonObj = JObject.Parse(jsonText);
string value = ((JObject)jsonObj)["functionTimeout"].ToString();
GetFileJson Method:
public static string GetFileJson(string filepath)
{
string json = string.Empty;
using (FileStream fs = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")))
{
json = sr.ReadToEnd().ToString();
}
}
return json;
}
Namespaces added:
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System.Text;
using System.IO;
Output:
My Function Class File:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace FunctionApp5
{
public static class Function1
{
[Function("Function1")]
public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
var logger = executionContext.GetLogger("Function1");
logger.LogInformation("C# HTTP trigger function processed a request.");
logger.LogInformation(GetEnvironmentVariable("functionTimeout"));
string jsonfile = "host.json";
string jsonText = GetFileJson(jsonfile);
JObject jsonObj = JObject.Parse(jsonText);
string value = ((JObject)jsonObj)["functionTimeout"].ToString();
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
response.WriteString("Welcome to Azure Functions!");
return response;
}
public static string GetEnvironmentVariable(string name)
{
return name ": "
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
public static string GetFileJson(string filepath)
{
string json = string.Empty;
using (FileStream fs = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")))
{
json = sr.ReadToEnd().ToString();
}
}
return json;
}
}
}