简体   繁体   中英

Cannot access web.config of ASP.NET Core Web API using ConfigurationManager in VS2022

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.

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:
在此处输入图像描述

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 .

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