0

The scenario is I created a class library for database connection. I also installed the System.Configuration.ConfigurationManager in this library.

Here is the code where the web.config access takes place:

public static class SqlDataAccess
{
    public static string GetConnectionString(string name)
    {
        string strCon = ConfigurationManager.ConnectionStrings[name].ConnectionString;
        return strCon;
    }
}

And this is the code where I output the connection string.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public string Get()
    {
        string connString = SqlDataAccess.GetConnectionString("db");
        return connString;
    }
}

When I access the WeatherForecast API, it should print out the connection string. But instead printing it out, it prints out an error:

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

The web.config file is in the ASP.NET Core Web API project and I added the class library as project reference.

This is the content of the web.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <connectionStrings>
        <add name="db" connectionString="{my connection string is in here}"/>
    </connectionStrings>
</configuration>

I have seen answers regarding this problem, but they still did not work in my case.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kroi
  • 246
  • 3
  • 9
  • 1
    Does this answer your question? [How to read web.config file in .Net Core app](https://stackoverflow.com/questions/46996480/how-to-read-web-config-file-in-net-core-app) – Yong Shun Jan 14 '23 at 04:09

1 Answers1

0

I used your given code and wrote a test controller, the only difference here was adding the configure file and naming it as app.config. Here is the result of my testing here, which is able to get the value form the file:
enter image description here

If you insist using web.config, which is created while you publishing your project, I may recommend you adding the value in appsettings.json instead of adding it in web.config.

Xiaotian Yang
  • 499
  • 1
  • 2
  • 7