configuration.GetConnectionString(“ MyConn”)获得空值? [英] configuration.GetConnectionString("MyConn") got null value?

查看:1630
本文介绍了configuration.GetConnectionString(“ MyConn”)获得空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下控制台应用程序(.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆