How To Get appsettings.json Data In Asp.Net Core MVC
In this tutorial is just want to show you, as the title said, how to get the data from appsettings.json using the built-in dependency injection in Asp.Net Core MVC.
Let’s start right away \o/
First, you need to create a project in visual studio. I’m using visual studio 2017 community with .net core version 1.1.
I’m creating an ASP.NET Core Web Application, that’s the new version of the mvc framework.
For the template, I’m choosing the Web Application template without authentication, we don’t need fancy stuff for this tutorial.
This is the basic structure of our solution, as we can see we have the appsettings.json file under the root of the solution. We don’t have the Web.config file anymore in the ASP.NET Core MVC, instead we have this file, that has a similar function. In the appsettings.json file, we can put all configurations needed for our project.
This is the default appsettings.json, with the default logging configuration of the .net core MVC framework.
For this tutorial I’ll add another configuration to the file:
I added the “HelloWorldObject” configuration to the file, and our objective here is to take the Text property and show it on the screen.
To be able to do that, we need to create a model that will store this data.
Done that, we have to configure the dependencies of this object, to able to inject it in our controller. The built-in dependency injection is all configured in the Startup class.
In the Startup class constructor, we have a set of configurations, one of them is the appsettings.json file. Using AddJsonFile() method, you are saying that a json file is a configuration file for the system, also you can have multiple configuration files.
Here, we’re adding two important configurations to the service container, AddOptions(), which allow us to use options, and with the extension method Configure<T>, we add an IConfigureOptions<T> service to the service container, in this case I’m saying that our HelloWordObject will the data from the “HelloWordObject” section in the appsettings.json file.
Now we can finally inject the IOption<T> object that we register in our controller.
Basically, in the HomeController constructor we put our IOptions<HelloWordObject> and the dependency injection framework will resolve it for us.
I made some changes to the index.cshtml page to just show the Text property from the HelloWordObject.
We can finally run the application and see the message in our browser.
As you can see, that’s our message on the screen.
Just one more thing before I finish, this is just a simple example of how you can get data from the appsettings.json, you can have complex objects too. You download the code and try to expand this sample for yourself!