[英]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.场景是我为数据库连接创建了一个 class 库。 I also installed the
System.Configuration.ConfigurationManager
in this library.我还在这个库中安装了
System.Configuration.ConfigurationManager
。
Here is the code where the web.config
access takes place:这是
web.config
访问发生的代码:
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.这是我 output 连接字符串所在的代码。
[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.当我访问
WeatherForecast
API 时,它应该打印出连接字符串。 But instead printing it out, it prints out an error:但它不是打印出来,而是打印出一个错误:
System.NullReferenceException: Object reference not set to an instance of an object.
System.NullReferenceException:Object 引用未设置为 object 的实例。
The web.config
file is in the ASP.NET Core Web API project and I added the class library as project reference. web.config
文件在 ASP.NET Core Web API 项目中,我添加了 class 库作为项目参考。
This is the content of the web.config
file:这是
web.config
文件的内容:
<?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 .我使用了您给定的代码并编写了一个测试 controller,这里唯一的区别是添加了配置文件并将其命名为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 .如果您坚持使用在发布项目时创建的web.config ,我可能建议您在appsettings.json中添加该值,而不是在web.config中添加它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.