2

I have an ASP.NET Core web application that has pulled in a .NET 4.6 class library. At some point in the class library there is a call to get a connection string from web.config:

ConfigurationManager.ConnectionStrings["AppDataConnectionString"].ConnectionString

(NOTE: I CAN NOT CHANGE THIS CODE.)

This class library has been used in old web forms applications, where the AppDataConnectionString was defined in their web.configs. Now I'm trying to use the class library in my ASP.NET Core web app, but the above code throws a null reference exception.

Here is the connection strings section in my web.config in the ASP.NET Core project:

<connectionStrings>    
    <add name="AppDataConnectionString" connectionString="server=xxxxxx;database=yyyyy;Trusted_Connection=yes;" providerName="System.Data.SqlClient" />
</connectionStrings>

I've also tried adding it in an appsettings.json file as follows:

{
  "ConnectionStrings": {
    "AppDataConnectionString": {
      "ConnectionString": "server=xxxxx;database=yyyyy;Trusted_Connection=yes;"
    }
  }
}

Here is where I load the configuration in Startup:

public IConfiguration _Configuration { get; set; }

public Startup()
{
    _Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(provider => _Configuration);             
}

public void Configure(IApplicationBuilder app)
{
    // Call some code from the class library that tries to get that connection string.
}

It seems to me like the configuration manager just can't find where the connection string is. Do I have my web.config or appsettings.json structured in the right way for it to find it?

1 Answer 1

4

It turns out that any configuration that was stored previously in a web.config file in previous versions of ASP.NET now needs to be stored in an app.config file in the same directory as project.json in ASP.NET Core. Now my imported class libraries can get their connections strings and everything works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.