amc software
amc software

Reputation: 865

ASP.NET Core Web API - ConnectionString in project reference

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

Upvotes: 0

Views: 1322

Answers (2)

Charles Han
Charles Han

Reputation: 2010

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 custom setting to reference the app settings from in the library project. Here is the reference.

Upvotes: 1

Ruikai Feng
Ruikai Feng

Reputation: 11621

It seems ConfigurationManager failed to read json file,have you tried add a .config file in your WebApi project? I tried two solutions as below :

public  class Class1
    {
        public  string? con1 { get; set; }

        public   string? con2 { get; set; }
        public readonly IConfiguration Config;

        public Class1()
        {
            //read connectstring from .config file
            con1 = System.Configuration.ConfigurationManager.ConnectionStrings["ReadConnectStringContext"].ConnectionString;
            Config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
            //read connectstring from appsettings.json
            con2 = Config.GetConnectionString("ReadConnectStringContext");
        }

    }

The structure:

enter image description here

The Result:

enter image description here

Upvotes: 2

Related Questions