简体   繁体   中英

Configuration manager can't get connection string in ASP.net 5

I have an ASP.NET 5 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 5 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 5 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?

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 5.0. Now my imported class libraries can get their connections strings and everything works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM