Home > Back-end >  Connection string from Web.Config not read by ConfigurationManager.ConnectionStrings["Test"
Connection string from Web.Config not read by ConfigurationManager.ConnectionStrings["Test"

Time:06-15

I have a connection string in my Web.Config file:

<configuration>
    <connectionStrings>
        <add name="Test" connectionString="MyConnString"/>
    </connectionStrings>
</configuration>

And am trying to access it in my code like this:

string connectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

Why am I receiving this error?

NullReferenceException: Object reference not set to an instance of an object.

ConfigurationManager.ConnectionStrings["Test"] is NULL but I can't figure out why.

I am using ASP.NET Core 3.1

I installed System.Configuration.Configuration version 6.0.0 using NuGet.

I have the correct using statement at the top of my code file: using System.Configuration;

CodePudding user response:

ASP.NET Core no longer uses the Global.asax and web.config files that previous versions of ASP.NET utilized.

The web.config file has also been replaced in ASP.NET Core. Configuration itself can now be configured, as part of the application startup procedure described in Startup.cs. Configuration can still utilize XML files, but typically ASP.NET Core projects will place configuration values in a JSON-formatted file, such as appsettings.json.

Read the following article: Migrate configuration to ASP.NET Core

So, you can rename the web.config to app.config.

But better solution is to update application to use JSON-formatted file, such as appsettings.json. For more information read the following article: Configuration in ASP.NET Core

  • Related