How to read multiple connectionstrings in appsetting.json file in .net core api project with CustomerID?

Viewed 306

I have customerId:- 1 and 2 and using this customer id i want to filter out my connection string

for example:-

"connectionstring":{
"connection_1":"data source"
"connection_2":"data source"
}

i want to read connection strings as per my customer id 1 and 2. Is it possible in .net core webAPI ? i want to access in dbcontext class or controller and change connectionstring dynamically.

1 Answers
"ConnectionStrings": {
    "FirstConnection": "Username=...;Password=...;Database=...;Host=...",
    "SecondConnection": "Username=...;Password=...;Database=...;Host=..."
  }

in code you can use below code:

configuration.GetConnectionString("FirstConnection")
configuration.GetConnectionString("SecondConnection")

or if extension method not found use below code:

configuration.GetSection("ConnectionStrings")[FirstConnection]
configuration.GetSection("ConnectionStrings")[FirstConnection]
Related