Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi -

What I am trying is to access my connection string(s) from the appsettings.json file. But string is always null. Any help is greatly appericated. Thank you in advance.

Appsettings
"customers":[
    {
      "name": "Customer One",
      "connectionStrings": [
        { "CustomerOneConnection": "" },
        { "CustomerTwoConnection": "" }
      ],
    }
]


Program.cs
inside the configure services accessing the app settings:

services.Configure<List<CustomerDetails>>(context.Configuration.GetSection("customers"));


Small class to set the details for the customer
    public class CustomerDetails
{
    public string name { get; set; }
    public List<Tuple<string, string>> connectionStrings { get; set; }

}



What I have tried:

_connectionString = customerDetails.connectionStrings.FirstOrDefault(x => x.Item1 == "CustomerOneConnection").Item1;

_connectionString = customerDetails.connectionStrings.Where(x => x.Item1 == "CustomerOneConnection").Item1;

_connectionString = customerDetails.connectionStrings[0].Item1;
Posted
Updated 22-May-23 22:56pm
Comments
Richard Deeming 23-May-23 3:40am    
Rather than List<Tuple<string, string>>, why not use Dictionary<string, string>? That will make it easier to retrieve the values, and you'll be less likely to look at Item1 when you mean Item2. :)

My suggestion would be to add the appropriate connection strings to appsettings.json so that the last lines read something like this


C#
"AllowedHosts": "*",
 "ConnectionStrings": {
   "CustomerOneConnection": "Data Source=(localdb)\\ProjectModels;Initial Catalog=Northwind;Integrated Security=True",
   "CustomerTwoConnection": "Data Source=(localdb)\\ProjectModels;Initial Catalog=Southwind;Integrated Security=True"
   }

Use a class to bind the connections to the public properties of the class. The names must exactly match the connection string names.


C#
public class ServerOptions
{
    //The field ConnectionStrings is not mapped,
    // Only the public properties are mapped to the connection strings
    // in appsettings.json
    public const string ConnectionStrings = "ConnectionStrings";

    public string CustomerOneConnection { get; set; } = string.Empty;
    public string CustomerTwoConnection { get; set; } = string.Empty;
}

Now you can bind the connection strings to the 2 public properties like this


C#
var serverOptions = new ServerOptions();
Configuration.GetSection(ServerOptions.ConnectionStrings).Bind(serverOptions);
 
Share this answer
 
THis should answer your question: .NET App Settings Demystified (C# & VB)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900