[EN] How to read data from appsettings.json in ASP.NET Core Web Api

In my previous post about token authentication in ASP.NET Core Web Api I mentioned that is not a good practice to hardcode strings in controller or Startup class, especially if we want to put some sensitive data like key for SigningCredentials or connection string to database or configuration parameters. How to avoid it? We can add all strings to configuration file. In ASP.NET Core we have appsettings.json file which is the right place to put these kind of data. It looks like this by default in Web Api project

ok let’s say we want to add few parameters here, for example data to generate token (in my previous post you can read about generating token) in CreateToken method in one of my Controllers – LoginController.  Here is the method we want to modify.

We want in this case to read issuer and audience from config file, the same with „SuperSecretKey” to generate SymmetricSecurityKey. First we need to add these data to appsettings.json.

Then we need to modify the LoginController where CreateToken method is located.

We need to use IConfigurationRoot object to read data from config file. Let’s add it as private field and inject it in controller.

Now it’s time to replace hardcoded strings in CreteToken method.

Unfortunately that’s not all. It will not work. There’s one step we need to do.  In Startup class we need to register IConfigurationRoot object as a singleton. There’s property called Configuration by default

and we need to add this line of code to ConfigureServices method

That’s all. Since we have known about appsettings.json file it’s good to use it.