I created a new AWS Serverless Application (.NET Core) and set up a Lambda function, but I want to read some information from an appsettings.json file like I would do with a normal ASP.NET Core 2 web app. How can I include an appsettings.json file and read a setting? I have some endpoints that I'd like to store and don't want to hard code those into my app.
You would do this the same way that you would add the configuration system to any non asp core project.
Add the following nuget packages to your serverless application:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.Json
Then add your appSettings.json
configuration file. Since you want the settings to be included in the published zip make sure to set Copy to Output Directory
to true
.
After this you can write some initialization code:
public IConfiguration Configuration { get; private set; }
private void ConfigureSettings()
{
Configuration = new ConfigurationBuilder()
.AddJsonFile("appSettings.json", optional: true)
.Build();
}
I am blind typing above so hopefully it works. If you wanted to use a strongly typed POCO instead of the Configuration you could use the Microsoft.Extensions.Configuration.Json
capability by doing something like this:
public ApplicationConfigPoco Configuration
{
get
{
return Configuration.Get<ApplicationConfigPoco>();
}
}
Lastly, since your Lambda runs on linux, be mindful of the case sensitivity that would not be present on a Windows system. For example appsettings.json
will not load if your file is appSettings.json
.