In this tutorial, you will learn how to add new keys in Appsettings.json file and read values from appsettings json file in asp.net core application.
Now you may not find any web.config file in Asp.net Core application, but to keep all standard configuration information like database connection string, SMTP information or any other custom configuration you may need to keep, now all will go in a file called Appsettings.json, but you still can continue with custom configuration framework if you have already used in your application.
Appsettings.json always contain values with key value pair separated with a colon like “Key”: “Value”
Now for each key you can have a single value or multiple values with a set of keys. you can write this way “section-key” :{ “key1”:”value1”, “key2”:”value2”}
There are multiple ways to read value from Appsettings.json file
First we learn simple way, like how we used to read value from web.config appsettings section.
In Asp.net Core we need to refer a namespace Microsoft.Extensions.Configuration; and then use IConfiguration to read the value from appsettings.json file.
private readonly IConfiguration config; public studentController(IConfiguration configuration) { config = configuration; }
using Microsoft.Extensions.Configuration; public class studentController : Controller { private readonly IConfiguration config; public studentController(IConfiguration configuration) { config = configuration; } public IActionResult index() { // Method 1 to read value string _dbCon1 = config.GetSection("DbConnectionConfig").GetSection("DatabaseName").Value; // Method 2 to read value string _dbCon2 = config.GetValue<string>("DbConnectionConfig:DatabaseName"); return View(); } }
Method 2
There is another we can get value from appsettings.json using custom class, like how we used to read using custom configuration in earlier .net version
See this code Illustration
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; public class HomeController : Controller { private readonly DbConnection dbconfig; public HomeController(IOptions<DbConnection> dbcon) { dbconfig = dbcon.Value; } }
Make sure you have registered the new section in ConfigureService method of Stratup.Cs
services.Configure<DbConnection>(Configuration.GetSection("DbConnectionConfig"));ConfigureService Method of Startup.Cs
You may also look at how to create entity framework core connection string and setup DbContext class.