Hi,
I am new to web api core,I have created one web api core with ado.net application.
I have declared a conenction string in appseeting.json,
I am trying new access in the controller but i am getting null value?
can any one help me how to access conenction string in controller from appsetting.sjon
step1
appsettins.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLOCALDB;Database=resource;Trusted_Connection=True;"
}
}
step 2
SqlConnection con1 = new SqlConnection(configuration.GetConnectionString("DefaultConnection"));
Prasad RaveendranPosted Aug 25, 2023, 11:11 PM
Since you are a beginner. its a good start with understanding the interface IConfiguration. However, I would recommend to explore the Options pattern - there are multiple ways to ready the AppSettings.json.
https://learn.microsoft.com/en-us/dotnet/core/extensions/options
Cr BhargaviPosted Aug 24, 2023, 5:35 AM
Please try adding
IConfigurationinterface into your controller and try the sameMohammad HussainPosted Aug 24, 2023, 4:38 AM
It looks like you're on the right track, but there's a missing piece in your code that's causing the
nullvalue. You need to inject theIConfigurationinterface into your controller so that you can access the connection string fromappsettings.json.Jaimin ShethiyaPosted Aug 22, 2023, 4:25 AM
Hello Hari,
Can you please check on your startup.cs file have you registered the configuration, if not then can you please add and try after that.
services.AddSinglton(configuration);
then after you can inject the IConfiguration into your API controller
private readonly IConfiguration _configuration;
public ValuesController(IConfiguration configuration)
{
_configration = configuration;
}
[HttpGet]
public IActionResult Get()
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
.......
}
Saravanan GanesanPosted Aug 16, 2023, 10:14 AM
In ASP.NET Core, inject
IConfigurationinto your controller's constructor. Use_configuration.GetConnectionString("DefaultConnection")to access the connection string fromappsettings.json. This allows you to create aSqlConnectioninstance for database operations within your controller methods. Ensure namespaces, class names, and methods match your codebase.Tahir AnsariPosted Aug 10, 2023, 2:09 PM
Amit MohantyPosted Aug 10, 2023, 1:42 PM
Try this
Rijwan AnsariPosted Aug 10, 2023, 1:05 PM
Hi
Try this way.