Home > other >  ASP.NET Core Web API - ConnectionString in project reference
ASP.NET Core Web API - ConnectionString in project reference

Time:01-27

I have a ASP.NET Core Web API project added to my solution. It uses a project dependency which connects to SQL Server database, using a connection string like this:

public string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

This works fine, another Web/WinForm Apps uses this library and connects to SQL Server instance (the connection string is set in the web.config or app.config)

The problem:

The ASP.NET Core Web API project fails to use the connection string from the library, I have set appsetting.json:

 "ConnectionStrings": {
    "ConnectionName": "Data Source=database;Initial Catalog=catalogname;User ID=username;Password=password;"
  },

But always the connection string with the connection name is null, and has:

data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

CodePudding user response:

Here is the documentation from MS:

Class libraries can access configuration settings in the same way as executable apps, however, the configuration settings must exist in the client app's App.config file. Even if you distribute an App.config file alongside your library's assembly file, the library code will not read the file.

A quick fix for you is to place the correct DB connection string section in the Web/WinForm Apps settings file.

If you really want to use the app settings from the library project, using a customm setting to refefence the app settings from in the libarary proejct. Here is the enter image description here

The Result:

enter image description here

  • Related