What if I want to create a quick console application and keep all my settings in a seperate appsettings.json file? The default C# application template doesn't provide this for us, so I think it might be useful to write a little guide to make this easier in the future.
Required
- .Net 5.0 console application
- The following packages: ```
### Guide ###
Simply follow these steps to load your appsettings into a class for easy use.
- Add the references above to the project
- Add a new class called `ApiSettings.cs`
public class ApiSettings
{
public string TwitterApiKey { get; set; }
public string TwitterApiSecret { get; set; }
public string BearerToken { get; set; }
}
- Add a new class called `Startup.cs`
public class Startup
{
public Startup()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false);
IConfiguration config = builder.Build();
ApiSettings = config.GetSection("ApiSettings").Get<ApiSettings>();
}
public ApiSettings ApiSettings { get; private set; }
}
- Add your `appsettings.json` with content similar to something like this:
{
"ApiSettings": {
"TwitterApiKey": "",
"TwitterApiSecret": "",
"BearerToken": ""
}
}
- Right click on the file `appsettings.json` and set the copy output to `Copy always`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdjm02cimlag0gbjim9g.png)
- Make sure the fields in the section 'ApiSettings' match your ApiSettings.cs class.
- Go back to your Program.cs file and add the following line:
`var startup = new Startup();`
- We can now use the values in the ApiSettings section of our appsettings. You can try it out with the following code.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypz58j3t175h5ruyi50z.png)
#All Done!#
<img width="100%" style="width:100%" src="https://media.giphy.com/media/VIjf1GqRSbf0OsNG0H/giphy.gif">
Now you can experiment and make it even more advanced yourself!
Top comments (3)
Your required section should be saying .NET 6 instead of .NET 5 as you are referencing .NET 6 NuGet packages.
Hey, thanks for your comment! The v6.0 packages actually work on a .net5 application in my example. I will update the article to reference the v5 packages to make it easier to understand for new readers.
You are welcome. I know that it works, I only mentioned it so we don't confuse new learners 🤣