configuration.GetConnectionString(“ MyConn”)获得空值? [英] configuration.GetConnectionString("MyConn") got null value?
问题描述
在以下控制台应用程序(.Net core 2.0)中, conn
具有空值。
In the following console application (.Net core 2.0), the conn
got a null value.
var services = new ServiceCollection();
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile("App.config", optional: false).Build();
services.AddSingleton(configuration);
var conn = configuration.GetConnectionString("MyConn"); // conn is null
以下是App.config。
The following is App.config.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConn" connectionString="....." />
</connectionStrings>
<Settings>
<Name>Test</Name>
</Settings>
</configuration>
有些代码可以获取的值(测试)
成功。设置
的名称
There is some code which can get the value ("Test") of Name
of the Settings
successfully.
更新:
在分配 conn
之后,我具有以下代码来获取< XML部分的Settings>
部分,它可以获取值 Test。
Right after the assignment of conn
, I have the following code to get <Settings>
section of the XML part and it can get the value "Test".
var myOptions = new MyOptions();
configuration.GetSection("Settings").Bind(myOptions);
推荐答案
请参见 GetConnectionString
只是扩展方法只需执行以下操作:
See, GetConnectionString
is just an extension method that simply do the following:
public static string GetConnectionString(this IConfiguration configuration, string name)
{
return configuration?.GetSection("ConnectionStrings")?[name];
}
如果在调试过程中检查了 Data
在配置中。提供者
对于
,您会发现以下键/值:
If during debugging you check Data
in configuration.Providers
for
you will find the following keys/values among others:
key: "connectionStrings:add:MyConn:name" | value: "MyConn"
key: "connectionStrings:add:MyConn:connectionString" | value: "....."
这就是为什么您得到的原因空
值。
That's actually why you got a null
value.
因此,使用当前的XML结构,您可以轻松地做到: p>
So with the current XML structure, you can simply do:
var connString = configuration.GetValue<string>("connectionStrings:add:MyConn:connectionString", string.Empty);
或将XML修改为
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<MyConn>conn_string_here</MyConn>
</connectionStrings>
</configuration>
并使用
var conn = configuration.GetConnectionString("MyConn");
// conn value will be "conn_string_here"
这篇关于configuration.GetConnectionString(“ MyConn”)获得空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!