8

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Ryan
  • 7,733
  • 10
  • 61
  • 106
  • Correct, `ConfigurationManager` is only for working with `web.config` and `app.config` files which are XML based (note that `WebConfigurationManager` isn't available in ASP.NET Core anyway). They do not support the JSON-based `appSettings.json` files. You must use ASP.NET Core's functionality for that. – Dai Oct 24 '18 at 03:58
  • Possible duplicate of [How to read AppSettings values from Config.json in ASP.NET Core](https://stackoverflow.com/questions/31453495/how-to-read-appsettings-values-from-config-json-in-asp-net-core) – Pranav Singh Oct 24 '18 at 06:55

1 Answers1

8

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();
Myonaiz
  • 326
  • 5
  • 14
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57