I have a .NET Standard library that contains all of my SQL related code. It even has some code in it that creates the SQL connection. This library needs to read from the application config file in order to grab the SQL connection string. The library is using the typical ConfigurationManager.ConnectionStrings
approach.
Now, I use this library in a .NET Core ASP.NET Web Api 2 application. I've got my connection string defined in this application's appsettings.json
file. The connection string is in the ConnectionStrings
field with a given name that matches the name that my DLL from above looks for.
This does not appear to work. My DLL, from the top section, does not find the connection string from the config file.
Does ConfigurationManager
not work with appsettings.json
? If not, how should I approach this?
ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.
Retrieves a specified configuration section for the current application's default configuration.
Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.
ConfigurationManager does not work with appsettings.json, instead of ConfigurationManager you have to use ConfigurationBuilder class for add json file in startup.cs file.
1.Put below code in appsettings.json
"ConnectionStrings": {
"connectionstring ": "Data Source=Demo_server\\SQLEXPRESS01;Initial Catalog=Demo_DB;Persist Security Info=True; User ID=sa;Password=Password@123" }
2.Put below code in startup.cs.
public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder().AddJsonFile("appSettings.json").Build();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
ConnectionString = Configuration["ConnectionStrings:connectionstring"]; // Get Connection String from Appsetting.json
}
3.Create ConnectionStringUtility class for get connection string from Startup.cs file.
public class ConnectionStringUtility
{
public static string GetConnectionString()
{
return Startup.ConnectionString;
}
}
4.Get Connectionstring in connection variable and use this connection string where ever you want.
public string Connectionstring = ConnectionStringUtility.GetConnectionString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With