Tuesday, 28 December 2021

Access Connection String In Asp.Net Core 6 Controller From appsettings.json C# | appsettings.json Connection String Value Access in Asp.net Core Controller

12/28/2021 - By Pranav Singh 0

In this article i will show you how you can access the connection string in controller from appsettings.json file content in asp.net core using c#.net.  In have already shown you how you can access connection string in DbContext.cs file from appsettings.json in asp.net core 6 application using c#.net


So for this first we will create a new aspo.net core application and run Scaffold-DbContext to make the connection with database. Here is the connection string which i present in appsettings.json file. 


"ConnectionStrings": {

    "sqlconnection": "Server=\\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;"

  }

 

Now we will add a controller class file and add the below code in you controller function where you want to access the connection string.


var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false);

            IConfiguration config = builder.Build();

            return config.GetValue<string>("ConnectionStrings:sqlconnection");

 

Now below are the reference you need to add in your application.


using Microsoft.Extensions.Configuration;

using System.IO;

 

Now we have done, run the application and check the output which you will get as show below.


appsettings value access in .net core

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top