In this post, we are going to learn how to read AppSettings values from a JSON file in ASP.NET Core.
Let’s start.
VIDEO: How to Read AppSettings Values From a JSON File in ASP.NET Core.
Read AppSettings Values From JSON File
Enabling a feature in ASP.NET Core almost always starts with configuring relevant components into the DI pipeline. This is also true for reading application settings from a JSON file. The good thing is that ASP.NET Core provides extra flexibility here. As long as we use the conventional filename, i.e. appsettings.json
, we don’t need any explicit setup for it. DI system will do it internally for us. In a later section, we will see how we can set up a different filename.
So, let’s assume we have an appsettings.json
file that defines some formatting options for our API:
{ "AllowedHosts": "*", "Formatting": { "Localize": false, "Number": { "Format": "n2", "Precision": 3 } } }
As we run the application, DI framework automatically pulls this piece of data in IConfiguration
service.
Read Values From IConfiguration
To see IConfiguration
in action, let’s add an API controller:
public class ConfigurationDemoController : ControllerBase { private readonly IConfiguration _configuration; public ConfigurationDemoController(IConfiguration configuration) { _configuration = configuration; } [HttpGet("formatting/islocalized")] public bool GetIsLocalized() { var localize = _configuration.GetValue<bool>("Formatting:Localize"); return localize; } }
We start with injecting IConfiguration
in the constructor. Later inside the GetIsLocalized
endpoint, we can retrieve the “Localize” option by calling _configuration.GetValue()
. To do this, we have to specify the full path of the target json-node, notably with “:” as the child node accessor.
We can extract the value of “Precision” similarly:
var precision = _configuration.GetValue<int>("Formatting:Number:Precision");
Pulling the whole “Formatting” group is also possible – by using a POCO model that resembles the target JSON tree.
The FormatSettings
:
public class FormatSettings { public bool Localize { get; set; } public NumberSettings? Number { get; set; } }
And the NumberSettings
:
public class NumberSettings { public string? Format { get; set; } public int Precision { get; set; } }
Now, we can easily map the “Formatting” section to a FormatSettings
instance:
var formatSettings = _configuration.GetSection("Formatting").Get<FormatSettings>();
This way of extracting group configurations is quite convenient. But not as much as it would with Options Pattern, especially if we need it in multiple places.
Using Options Pattern
To start using the options pattern for reading FormatSettings
, we need to configure it with DI first.
Let’s do it in Program
class:
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.Configure<FormatSettings>(builder.Configuration.GetSection("Formatting")); builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();
All we need is to add the highlighted line in this boilerplate code. With the help of the Configure()
extension method, we establish the “Formatting” section as the data source of FormatSettings
.
This enables easy access to FormatSettings
just by injecting IOptions<FormatSettings>
anywhere we need it:
public class OptionsDemoController : ControllerBase { private readonly FormatSettings _formatSettings; public OptionsDemoController(IOptions<FormatSettings> options) { _formatSettings = options.Value; } [HttpGet("formatting")] public FormatSettings Get() => _formatSettings; }
This is much simpler and the recommended way to deal with configuration groups.
Register JSON File With Unconventional Name
It’s time to see how to register an arbitrary JSON configuration file.
So, if we want to set up a “config.json” file as the source of application configuration:
// Add services to the container. builder.Host.ConfigureAppConfiguration(config => { config.AddJsonFile("config.json"); }); builder.Services.Configure<FormatSettings>(builder.Configuration.GetSection("Formatting")); builder.Services.AddControllers();
We can register it using a host configurator extension named ConfigureAppConfiguration
. Inside its closure, we just need to call AddJsonFile()
. As simple as that.
Read AppSettings Outside of DI
Sometimes we need to read configurations outside of ASP.NET Core DI. This is a typical case when we work with design time execution or CLI tools like generating database migration files (Entity Framework Core) for example.
Dependencyless ConfigurationBuilder
class comes in handy for such cases:
var configuration = new ConfigurationBuilder() .AddJsonFile("config.json") .Build(); var precision = configuration.GetValue<int>("Formatting:Number:Precision");
We can get a default IConfiguration
just by adding the target json file to the builder. The rest is no different than our previous examples.
Conclusion
In this article, we have discussed various approaches to read configurations from a JSON file in ASP.NET Core.
Hi team, i want to read the AppSettings in a static file with no DI Iconfiguration, is that possible in .nET 7
Hi Vijay, yes possible. You can retrieve the physical path of a static file using host-environment file provider and then using the approach we mentioned in “Read AppSettings Outside of DI” section (code sample attached at the bottom). However, I would not recommend static files for such purposes because of high-security risks.
I used this in net core 7 _configuration.GetSection(“EmailSettings”)[“Password”] and it works, am I doing it wrong?
in appsettings:
“EmailSettings”: {
“Host”:””,
“Password”: “”
}
Hi Coby, thanks for reading and commenting.
Yes, you’re right. You can do this too to read a nested field. But for reading a single value, I find GetValue<T> more convenient as it readily casts to specific data-type, no hassle of further conversion which is the case when we use index notation (returns value as string).
You made my day
Glad you find it useful 🙂
It would be helpful if you put some using statements so I can find out what NuGet packages you are using.
Hi Bruno. Well, there is really no need for that. We provide the source code for each of our articles, so by checking that you will find that none of the packages are used here. Also, you can download the source code and inspect it yourself to see all the using statements that are required. Finally, if you are coding alongside the article, Visual Studio will provide all the necessary namespaces. Just check the link at the top of the article for the source code.
Well, I understand Marinko’s answer which encourages readers to go deeper and download the full repo to get the answer to their questions (I just did).
But hey, I would have loved this answer too :
Nuget packages :
Namespace used :
This info could be added to the top of each code examples to make this article even more awesome 🙂
Hi Manitra.
Thank you for your comment and for the kind words, this means a lot to us.
About your suggestions. Well, for this article, because we used ASP.NET Core Web API project, we didn’t install any of the mentioned libraries, they all come preinstalled. That’s why we didn’t have to mention anything about them. As you can see our first sentence: “In this post, we are going to learn how to read AppSettings values from a JSON file in ASP.NET Core.” – it is clear that we are using the ASP.NET Core project.
About namespaces, again, as soon as we start typing in VisualStudio, you get those automatically applied, and yes, we have a source code. But since, obviously, you are not the only one asking for this, maybe we will change the way we structure our code snippets. For me, those namespaces just add to the confusion with so many code lines. Again, they will be automatically added to your project once you start coding.
There are so many articles published on the internet without a source code, and we, for each of our articles have that, so that’s a great advantage for all of our readers. Why not use that opportunity to download the working code and have it right next to you while reading or coding with the article? At least, this is my opinion, and how we, currently, organize all of our articles on the site.