Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ConfigurationManager work with ASP.NET core's appsettings.json?

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?

like image 433
Ryan Avatar asked Oct 24 '18 03:10

Ryan


People also ask

Does ConfigurationManager work in .NET Core?

ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.

What is ConfigurationManager Appsettings?

Retrieves a specified configuration section for the current application's default configuration.

Does .NET Core support app config?

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.


1 Answers

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();
like image 93
AddWeb Solution Pvt Ltd Avatar answered Nov 15 '22 05:11

AddWeb Solution Pvt Ltd