I have created AWS Lambda Project in C# (NOT Serverless Application)

I have defined a Environment variable in aws-lambda-tools-defaults.json as below
"environment-variables": {
 "my-api": "http://myapihost.com/api/attendance-backfill"
 }
In Function.cs, fetching the value as below
   var apiUrl = Environment.GetEnvironmentVariable("my-api").ToString();
but it always coming as null.
How do I set & fetch Environment variable?
Thanks!
As per comment.


It's pretty close but after some digging around I found out how to actually set these for local runs using the Mock Lambda Test Tool. It is, in-fact, inside the launchSettings.json file. You want to drop the settings inside the Mock Lambda Test Tool section of the profiles node, not outside it.
{
 "profiles": {
  "Mock Lambda Test Tool": {
   "commandName": "Executable",
   "commandLineArgs": "--port 5050",
   "workingDirectory": ".\\bin\\Debug\\netcoreapp2.1",
   "executablePath": "C:\\Users\\%USERNAME%\\.dotnet\\tools\\dotnet-lambda-test-tool-2.1.exe",
   "environmentVariables": {
     "environment": "test"
   }
  }
 }
}
                        There are two places where you’ll need to set environment variables: development-time and deployment-time. To do this, open the launchSettings.json file from under the Properties folder in the Solution Explorer. Then add the following JSON property:
    "environmentVariables": {
      "my-api": "something"
    }
To set environment variables at deployment-time, you can add these to the aws-lambda-tools-defaults.json file. (Just remember to escape the double quote marks.)
    environment-variables, its format is: "<key1>=<value1>;<key2>=<value2>;".
In your case you should have
    "environment-variables" : "\"my-api\"=\"http://myapihost.com/api/attendance-backfill\";"
Consuming/fetching the environment variables
Consuming the environment variables as part of the Lambda function’s logic is done intuitively in the C# code, by using the System library aws blog:
System.Environment.GetEnvironmentVariable(<key>);
In your case you can use the following;
var apiUrl = System.Environment.GetEnvironmentVariable("my-api");
In this document it is suggested that your approach for fetching environment variable is correct.
    var variableValue = Environment.GetEnvironmentVariable("nameOfVariable"); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With