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.