运行.net core 2.1 AWS Lambda函数时,使用以下命令从c#中的AWS Lambda控制台获取环境变量很简单:
var envVariable = Environment.GetEnvironmentVariable("myVariableName");
但是,当在AWS Lambda上将ASP.NET core 2.1作为无服务器应用程序运行时,此操作无效(以上返回null)。
我可以在launchSettings.json文件中设置一个 local env变量,但是我想从AWS Lambda控制台中使用Env变量。
如何在ASP.NET Core 2.1中访问AWS Lambda Env变量?
答案 0 :(得分:18)
如何在ASP.NET Core 2.1中访问AWS Lambda Env变量
您可以像以前一样访问它。
var envVariable = Environment.GetEnvironmentVariable("myVariableName");
确保已为相应资源设置了环境变量,以便在调用时可用。
每个资源在 serverless.template 文件中都有一个条目,该文件是用于部署功能的AWS CloudFormation模板。
环境变量条目位于文件的Resources:{ResourceName}:Properties:Environment:Variables
JSON路径下。
示例声明
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Transform" : "AWS::Serverless-2016-10-31",
"Description" : "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",
"Parameters" : {
},
"Conditions" : {
},
"Resources" : {
"Get" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
"Handler": "TimeZoneService::TimeZoneService.LambdaEntryPoint::FunctionHandlerAsync",
"Runtime": "dotnetcore1.0",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 60,
"Role": null,
"Policies": [ "AWSLambdaFullAccess" ],
"Environment" : {
"Variables" : {
"myVariableName" : "my environment variable value"
}
},
"Events": {
"PutResource": {
"Type": "Api",
"Properties": {
"Path": "/{proxy+}",
"Method": "ANY"
}
}
}
}
}
},
"Outputs" : {
}
}
引用Build and Test a Serverless Application with AWS Lambda
引用Creating a Serverless Application with ASP.NET Core, AWS Lambda and AWS API Gateway
答案 1 :(得分:0)
尝试一下:
public interface IEnviromentVariables {
string getEnVariable(string variable);
}
public class EnviromentClass : IEnviromentVariables {
public string getEnVariable(string variable) {
return System.Environment.GetEnvironmentVariable(variable);
}
}