It seems to be simple, but it is not working for me…
I am using C#.NET 6.0 for AWS Lambda Function. I am trying to create this Function in Visual Studio 2022. There is no Startup.cs file in this Lambda Function Project. Just a Class Library with Function.
I just want to read the values from appsettings.json file from C# Function. The Json File looks like this…
{
"SQSARN": "arn:aws:sqs:us-east-1:111111111111:SQS-Queue1",
"BucketName": "excel-s3-bucket",
"ObjectKey": "Sample.xlsx"
}
I am reading the values in C# Code as below…
config = new ConfigurationBuilder().AddJsonFile("appsettings.json",true,true)
.SetBasePath(Directory.GetCurrentDirectory())
.Build();
Now I am trying to extract as below…
string myValue = config.GetValue<string>("SQSARN");
I am getting Null value for the above key.
Where am I going wrong here? Any libraries needs to be added here? Please let me know.
>Solution :
This is how I add JSON settings files. I’ll assume the file is called appsettings.json, and it contains a key "BucketName"
- Add NuGet package
Microsoft.Extensions.Configuration.Json - Right-click Project > Add > New Item… > JSON file
- Add all your settings in your JSON file
- Json File Properties > Copy to Output Directory = "Copy Always"
Then you can access the settings with code similar to:
using Microsoft.Extensions.Configuration;
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json");
var config = configuration.Build();
var bucketName = config["BucketName"];