我有一个包含许多项目的解决方案。
其中一个项目是数据访问层类库。它使用此行作为连接字符串,它从引用它的任何其他项目的web.config获取:
private string Constr = ConfigurationManager.ConnectionStrings["DefaultConn"].ConnectionString;
我已将web.config添加到.net核心2 MVC应用中,但我收到此错误:
FileNotFoundException:无法加载文件或程序集 ' System.Configuration.ConfigurationManager,Version = 0.0.0.0, Culture = neutral,PublicKeyToken = 123456'。系统找不到了 指定文件。
我还尝试将连接字符串添加到appsettings.json文件中 - 但它也没有帮助; appsettings.json的全部内容:
{
"ConnectionStrings": {
"DefaultConn": "Server=.;Database=MyDatabase;Trusted_Connection=true;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
我发现有几篇文章在网上围着它跳舞 - 但没有一篇可以解决这个问题。
How to read web.config file in .Net Core app 这个提到了类似的情况和一个nuget包 - 但它并没有解决用户的问题。
How to include reference to assembly in ASP.NET Core project 这个涉及它但仅适用于Hangfire,而不适用于使用ConfigurationManager的类库
我该怎么做?感谢。
答案 0 :(得分:0)
我意识到理想情况下你会使用DI和appsettings.json在.net核心MVC 2中存储连接字符串。
但是,关于我的具体问题 - 将连接字符串传递给类库,该类库已经预期来自web.config - 并且有助于转换到.net核心 - 另一个问题很有用: How to read web.config file in .Net Core app
但没有答案回答 - Zuhair的评论。基本上只需重命名web.config app.config即可。它也适用于链接类库。
这是我的app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=.;Database=mydb;Trusted_Connection=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
您还需要安装此NuGet包:
System.Configuration.ConfigurationManager