【发布时间】: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