How to read Connection string from Appsetting.json in ASP.NET Core
Vivek Jaiswal |
34639 |
{{e.like}} |
{{e.dislike}} |
In this Article, we will discuss way for define Connection String and retrieve that key value pair from Appsettings.json in ASP.NET CORE. Appsetting.json is similar to web.config but it is in JSON format. In ASP.NET Core we have a file named appsetting.json to store similar information like web.config. My blog post is all about how to inherit or read any global variable that we set in Appsettting.json by key value pair. So old way that we set connection string in web.config is not work here.
The way of reading the connectionstring in key and value pair in .NET Core application in following steps.
Step1: Open Visual Studio 2017 and select here ASP.NET CORE 2.0 project template.
Step2: Open Appsettting.json file and add following code snippet for adding connectionstring.
Appsetting.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"Data": {
"ConnectionString": "Data Source=ADMINRG-N8EO0RN\\SQLEXPRESS;Initial Catalog=testdb;Integrated Security=True"
}
}
Step3: Add Custom class for accessing the connection string from Appsetting.json
Step4: Now in order to read the data of connection string in db class, write following code snippets.
public class db
{
SqlConnection con;
public db()
{
var configuation = GetConfiguration();
con = new SqlConnection(configuation.GetSection("Data").GetSection("ConnectionString").Value);
}
public IConfigurationRoot GetConfiguration()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
}
Here configuration in ASP.NET Core is based on key value pairs established by configuration providers. Configuration providers read the configuration data into key-value pair from various types of data types.
We also create constructor in which we call configuration function and initialize this value into SQL connection object.
This is the all the above to access connectionstring or any other key value pair that is added into Appsettting.json file.
Thanks.
If you like this article don’t forget to share this article with your friends.
Comments
Follow up comments |
{{e.Name}} {{e.Comments}} |
{{e.days}} | |
|
||
|
{{r.Name}} {{r.Comments}} |
{{r.days}} | |
|