Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading appsettings.json values from C#.NET 6.0 AWS Lambda Function

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.

like image 851
CPK_2011 Avatar asked Apr 18 '26 14:04

CPK_2011


1 Answers

This is how I add JSON settings files. I'll assume the file is called appsettings.json, and it contains a key "BucketName"

  1. Add NuGet package Microsoft.Extensions.Configuration.Json
  2. Right-click Project > Add > New Item... > JSON file
  3. Add all your settings in your JSON file
  4. 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"];
like image 190
SSS Avatar answered Apr 21 '26 04:04

SSS