如何在 Azure Function 的构造函数中读取 local.settings.json 文件中的变量?
How to read the variables from local.settings.json file in the constructor in Azure Function?
我有以下代码并做了一些修改,现在我想移动 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);
}
在构造函数中使用名为 IConfiguration Class 的依赖注入,如下所示:
在 .Net 6(可能还有一些更早的版本)中使用 IConfiguration 注入,我们可以读取 local.settings.json
文件
public Function1(IConfiguration configuration)
{
string setting = _configuration.GetValue<string>("MySetting");
}
MySetting
必须在 local.settings.json
的 Values
部分:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"MySetting": "value"
}
}
参考文献: Azure Functions with Configuration and Dependency Injection - PureSourceCode
我有以下代码并做了一些修改,现在我想移动 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);
}
在构造函数中使用名为 IConfiguration Class 的依赖注入,如下所示:
在 .Net 6(可能还有一些更早的版本)中使用 IConfiguration 注入,我们可以读取 local.settings.json
文件
public Function1(IConfiguration configuration)
{
string setting = _configuration.GetValue<string>("MySetting");
}
MySetting
必须在 local.settings.json
的 Values
部分:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"MySetting": "value"
}
}
参考文献: Azure Functions with Configuration and Dependency Injection - PureSourceCode