在我的 ASP.NET MVC 项目(在 .NET 4.8 上)中,我有一个带有此工作连接字符串的
web.config
:
<connectionStrings>
<add name="SystemConnectionString"
connectionString="Server=10.10.10.10; Port=1000; Database=SampleDB; User Id=user1; Password=aaa;"
providerName="Npgsql" />
</connectionStrings>
我正在尝试将其从
web.config
中删除,想法是将其放入本地 XML 文件中,从而避免将此信息推送到云存储库。
我已经制作了这个 XML(没有
providerName="Npgsql"
,我稍后会提到):
<connectionStrings>
<add name="SystemConnectionString"
connectionString="Server=10.10.10.10; Port=1000; Database=SampleDB; User Id=user1; Password=aaa;" />
</connectionStrings>
我创建了这段代码:
public class SystemEntities : DbContext
{
private static SystemEntities instance;
public static SystemEntities Instance()
{
lock (typeof(SystemEntities))
if (instance == null)
instance = new SystemEntities();
return instance;
}
public SystemEntities() : base(nameOrConnectionString: GetConnectionString())
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
private static string GetConnectionString()
{
string filename = "ConnectionStrings.xml";
// Get the path to the XML file containing connection strings
string documentPath = ConfigurationManager.AppSettings["keysFolder"]; //keysFolder is set at web.config
string xmlFilePath = Path.Combine(documentPath, filename);
if (!File.Exists(xmlFilePath))
throw new FileNotFoundException("Error: file not found");
// Load the XML file
XDocument doc = XDocument.Load(documentPath + filename);
// Retrieve the connection string by name
string connectionString = doc.Descendants("add")
.Where(a => a.Attribute("name")?.Value == "SystemConnectionString")
.Select(a => a.Attribute("connectionString")?.Value)
.FirstOrDefault();
if (string.IsNullOrEmpty(connectionString))
throw new ConfigurationErrorsException("Error: connection strings not found");
return connectionString;
}
}
当我尝试上面的代码连接到 postgres 数据库时,我收到此错误:
28000:主机“10.10.10.10”、用户“user1”、数据库“template1”没有 pg_hba.conf 条目,无加密
在我看来,连接字符串不正确,因此导致了这种情况。另外,如果我将数据库从
pg_hba.conf
更改为 all
,那么我就可以连接到数据库。
查看此代码时,我确实注意到
providerName="Npgsql"
未包含在从 XML 文件获取的连接字符串中,这可能是导致此问题的原因。我尝试将 Npgsql
添加到字符串中,但没有成功。
有人可以评论一下吗?
我不知道您的项目中是否有多个连接字符串,并且您只希望其中一些位于外部文件中。但是,如果所有连接字符串(或总共只有这一个)都位于外部文件中,则无需编写手动读取该文件的代码。 ASP.NET 支持使用
web.config
属性将一个 configSource
文件拆分为多个文件。在您的示例中,您的 web.config
看起来像这样:
<?xml version="1.0"?>
<configuration>
<connectionStrings configSource="ConnectionStrings.xml" />
</connectionStrings>
ConnectionStrings.xml
将包含 connectionStrings
的根元素,它将添加示例中的连接字符串:
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="SystemConnectionString"
connectionString="Server=10.10.10.10; Port=1000; Database=SampleDB; User Id=user1; Password=aaa;"
providerName="Npgsql" />
</connectionStrings>