configuration.GetConnectionString(“MyConn”) got nu

2019-04-30 18:50发布

问题:

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

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.

Update:

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);

回答1:

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];
}

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.


So with the current XML structure, you can simply do:

var connString = configuration.GetValue<string>("connectionStrings:add:MyConn:connectionString", string.Empty);

Or modify your XML to

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <MyConn>conn_string_here</MyConn>
  </connectionStrings>
</configuration>

and use

var conn = configuration.GetConnectionString("MyConn");
// conn value will be "conn_string_here"


回答2:

.NET Core's Configuration does not treat .config files any different than XML files. That is, you can't add the connection string "the old way", by having an add tag, as this would create quite weird config keys:

If you want to use XML files, the correct way of specifying the connection string would be:

<connectionStrings>
  <MyConn>....</MyConn>
</connectionStrings>


标签: c# .net-core