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; |
0 comments:
Please let me know your view