In asp.net core, parameters such as database connection strings , service-related configurations, data that is rarely changed are placed in the appsettings.json file and must be load from appsettings.json whenever needed from IConfiguration To use. In this article, we will discuss how to read data from appsettings.json. Consider the following appsettings.json file where we want to get the value of the Name parameter inside the controller:

{
  "Name": "Farhad"
}

To read this data, the first solution is to get the Name value through the IConfiguration interface. To do this, we must first get the IConfiguration interface from the DI and get the value of the Name parameter inside the method:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public WeatherForecastController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var name = _configuration["Name"].ToString();
        return Ok(name);
    }
}

 In the Get method, we get the value of the Name parameter from the IConfiguration and put it inside the name variable. The IConfiguration interface refers to the root of the appsettings.json file, and the Name parameter is located in the root of the appsettings.json file, so we can get the value of the Name parameter directly. If we use the IConfiguration interface to read data, the IConfiguration interface gives us the latest changes whenever a change is made to the appsettings.json file. For example, if while the program is running and you change the value of the Name parameter, when it reaches the Get method, it puts your last changes in the name variable.

If the structure of your parameters in the appsettings.json file is an object or array, you should read the data differently. Consider the following appsettings.json file structure with some string connection parameters in the ConnectionStrings section:

{
  "ConnectionStrings": {
    "SqlServer": "Data Source=.; Initial Catalog=ConfigurationDB; Integrated Security=True;",
    "MongoDb": "mongodb://localhost"
  }
}

If we want to get the SqlServer connection, we have to do the following:

[HttpGet]
public IActionResult Get()
{
    var connectionString = _configuration["ConnectionStrings:SqlServer"].ToString();
    return Ok(connectionString);
}

We have to put the sign : after the name of the desired section . Similarly, if there is another section in the ConnectionStrings section, we can refer to the following sections by placing the : sign .

The problem with this method is that every time we want to read data from appsettings.json we have to manually enter the names of sections and parameters. The solution to this problem is to use a model. That is, to create a class and specify the parameters we want to receive as a property within the model. For example, for the upper part of the string connection, which has two connectors, SqlServer and MongoDb, we need to create a class as follows:

public class ConnectionStrings
{
    public string SqlServer { get; set; }
    public string MongoDb { get; set; }
}

Then we need to register this class in the ConfigureService method in the Startup class:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ConnectionStrings>(a => Configuration.GetSection(nameof(ConnectionStrings)).Bind(a));

    services.AddControllers();
}

In the Configure method, we specify that for the ConnectionStrings class, it must read the data from the section (nameof (ConnectionStrings)), which is the same as ConnectionStrings, and set its value in the properties of the ConnectionStrings class. Then, to read the information from the registered model, we must do the following using the IOptions interface located in the Microsoft.Extensions.Options library:

private readonly ConnectionStrings _configuration;

public WeatherForecastController(IOptions<ConnectionStrings> configuration)
{
    _configuration = configuration.Value;
}

[HttpGet]
public IActionResult Get()
{
    var sqlServer = _configuration.SqlServer;
    return Ok(sqlServer);
}

With this method, wherever you want to get the value of the SqlServe and MongoDb string connections in the program, you do not need to use IConfiguation and write all the properties of its properties manually, just get the model using IOptions. And use its properties.

Powered by Froala Editor