BLAZORLOVER
BLAZORLOVER

Reputation: 2011

Can't read connection string from web.config

I have the following in my web.config located at the root of my project:

<configuration>
  <connectionStrings>
    <clear />  
    <add name="Default" providerName="System.Data.SqlClient" connectionString="Server=tcp:whoops;Encrypt=True;TrustServerCertificate=False;Connection Timeout=3000;" />
  </connectionStrings>
  <appSettings>
    <add key="ConnectionString" value="test"/>
  </appSettings>
  ....

I read from Startup.cs (this is an asp.net core web app):

 string connection = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

However when I break on this, ConfigurationManager.ConnectionStrings and ConfigurationManager.AppSettings are empty (well, the first has some default connection string that is not the one in web.config).

What's going on here?

Upvotes: 1

Views: 1500

Answers (2)

0909EM
0909EM

Reputation: 5037

Not saying this is how you should do it, but you can do the following...

In ASP.Net Core 2.2, you should be able to add an XML configuration to IConfigurationBuilder using

configBuilder.AddXmlFile("app.config");

Contents is pretty much the same as above...

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings configSource="connectionStrings.config" />
  <appSettings>
    <add key="Test" value="TestValue" />
  </appSettings>
</configuration>

You should then be able to access AppSettings/ConnectionStrings using...

ConfigurationManager.ConnectionStrings

ConfigurationManager.AppSettings.AllKeys
{string[1]}
    [0]: "Test"
ConfigurationManager.AppSettings.Get("Test")
"TestValue"

Upvotes: 3

MoustafaS
MoustafaS

Reputation: 2031

You will have to migrate the config to the new file appsettings.json https://learn.microsoft.com/en-us/aspnet/core/migration/configuration?view=aspnetcore-2.1

Upvotes: 2

Related Questions