How to read and store connection string in appsettings.json
Loading
How to read and store connection string in appsettings.json
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Uday DodiyaPosted Sep 27, 2022, 7:32 AM
In .NET Core and ASP.NET Core applications the application settings are stored in a JSON file named appsettings.json. This is the default configuration for .NET Core projects. INI and XML files is also supported but JSON is the default.
Method 1: Using the standard location
To define the connection strings in appsettings.json it is important to specify it in the right section of the JSON structure.
Now we can read it in our code by calling the GetConnectionString method in the Microsoft.Extensions.Configuration namespace.
To be able to call the method you must import the Microsoft.Extensions.Configuration namespace like this:
Method 2: Using a custom appsettings structure with sections
If you want to structure your settings in a way more logical to your app it is possible to locate your connection strings whereever you want and still be able to access them in code.
In this scenario we do not use the GetConnectionString method in the Microsoft.Extensions.Configuration namespace. Instead we use the GetValue method and use colon ":" to represent the hierarchy.
Accessing the Configuration object
For the above methods to work we need access to the configuration object ("_configuration" in the above samples) which is an IConfiguration. This object is registered in the .NET Core IoC container so we can easily get access to it through dependency injection.
Access configuration in Startup.cs
Access configuration in ASP.Net MVC controller
About settings in .NET Core
Please note that this article only demonstrates a few easy ways to work with connection strings specifically. There is many other ways to work with configuration settings in .NET Core. For instance:
Rajanikant HawaldarPosted Sep 27, 2022, 6:10 AM
https://www.c-sharpcorner.com/article/setting-and-reading-values-from-app-settings-json-in-net-core/
https://www.c-sharpcorner.com/article/all-about-appsettings-in-asp-net-core/
Sachin SinghPosted Sep 27, 2022, 5:17 AM
There are multiple ways like
you can read it using IConfiguration one by one or can directly bind to any Class with the same properties.
to just get the connection string
Vishal YelvePosted Sep 27, 2022, 5:11 AM
Hi Naresh,
In appsetting.json
If you are using .net core 3.1
In Startup.cs class inside ConfigureService
If you are using .NET 6
In Program.cs file
Amit MohantyPosted Sep 27, 2022, 4:56 AM
Check the article
https://www.aspsnippets.com/Articles/Net-Core-Read-Connection-String-from-AppSettingsjson-file.aspx