This seems to be simple and should be common but I’m not familiar with Visual Studio 2022, I’ve created a Web API, and this API needs some keys that usually I just write on the web.config/app.config as keys and retrieve it on the code through configuration manager. What I have right now is appsettings.json which I’m not familiar. I don’t know how to write my keys here and retrieve on my code so I can use them. Maybe someone could guide me on how to work on this.
With the web.config, I just wrote this down like this:
<add key="Key1" value="SomeInfo"/>
And retrieve it like this on my code:
string keyInfo1 = ConfigurationManager.AppSettings["Key1"];
I tried to google. Unfortunately, I did not understand. Maybe it’s not what I’m looking for.
1
In order to make it work, you need some things actually.
I will take an example of plain console application to show what packages are involved and what steps needs to be taken.
So, having plain console app we need to add packages Microsoft.Extensions.Configuration
and Microsoft.Extensions.Configuration.Json
.
Then the configuration file cna be references like follows:
using Microsoft.Extensions.Configuration;
// Create instance of configuration builder
// and define source from json file.
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
// Build the configuration based on provided information.
.Build();
Console.WriteLine(configuration["Foo"]);
Finally, to make it fully work, add appsettings.json
file and set its property “Copy to output directory” as to “Copy always” or “Copy if newer”.
ASP.NET Web API
The project template should contain correctly configured appsettings.json
file and by accessing IConfigration
object you can read the provided configuration.
If something is not working, I suggest trying above steps to see if that would help.