Easy Steps
- Add appSettings.json
- Install nuget: Microsoft.Extensions.Configuration(include FileExtensions and Json)
- Use the ‘ConfigurationBuilder’ to build key/value based configuration settings for use in the application
1. Add an AppSettings.json File
Right-click on the project and select ‘Add New Item’. In the search box type ‘json’ keyword and select ‘JavaScript JSON Configuration File’. Rename jsconfig1.json to the ‘appSettings.json’.
The ‘appSettings.json’ content:
2. Install Microsoft.Extensions.Configuration Libraries
The next libraries required to read configuration from the appSettings.json file:
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
Use ‘Manage NuGet Packages…’ menu option and find Microsoft.Extensions.Configuration libraries.
3. Read Connection string using ConfigurationBuilder and IConfiguration
By using ConfigurationBuilder, you can store configuration values in a JSON file, for example, and then retrieve them at run time. The Build method creates IConfiguration with keys and values from the appSettings.json. And using the extension method GetConnectionString you retrieve the value of your connection string. And do not forget to set ‘Copy to Output Directory’ to ‘Copy always’ otherwise appSettings.json won’t be found.
C# code
using System; using System.IO; using Microsoft.Extensions.Configuration; namespace AppJsonConnectionString { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true); IConfiguration _configuration = builder.Build(); var myConnectionString1 = _configuration.GetConnectionString("MyConnectionString1"); Console.WriteLine(myConnectionString1); } } }
Excelente! Me fue de gran ayuda. Muchas gracias.