0

I am new to .net core ,and I am trying to make a method which can add new connection string to appseeting.json file , the project that we are trying to achieve that we have deferent database for every client with the exact design for all the databases

my Connection section in appseeting.json look like this

"AllowedHosts": "*",
"ConnectionStrings": {
"ConnStr": "Data Source=.;Initial Catalog=S_Center;User ID=sa;Password=zsa"
 },

and I want to make this method to add the new connection string

[HttpPost]
[Route("SetConnection")]
 public async Task<IActionResult> SetConnection(string server , string databaseName , string user , password)
            {
///what should I do here
            }

i have done this befor with .net and it was like this


[HttpPost]
[Route("SetConnection")]
 public async Task<IActionResult> SetConnection(string server , string databaseName , string user , password)
{
 string str = "server=" + server + ";database=" + databaseName + "; User ID=" + user + "; Password=" + password + "";
                Configuration myConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
                str = WebConfigurationManager.AppSettings["myKey"];
                myConfiguration.Save();
                System.Configuration.Configuration Config1 = WebConfigurationManager.OpenWebConfiguration("~");
                ConnectionStringsSection conSetting = (ConnectionStringsSection)Config1.GetSection("connectionStrings");
                ConnectionStringSettings StringSettings = new ConnectionStringSettings("GConnection", "Data Source=" + A + ",1433;Initial Catalog=" + B + ";Integrated Security=False;User Id=" + C + ";password=" + D + "", "System.Data.SqlClient");

                conSetting.ConnectionStrings.Remove(StringSettings);
                conSetting.ConnectionStrings.Add(StringSettings);
                Config1.Save(ConfigurationSaveMode.Modified);
return ok();

}
````````````
  • googling can find you some results, like this https://stackoverflow.com/questions/41653688/asp-net-core-appsettings-json-update-in-code – King King Mar 06 '21 at 17:29

1 Answers1

0

The use of ImplementationFactory overload of the IServiceCollection in the ConfigureServices method may be your answer. please take a look at this.

Majid Shahabfar
  • 4,010
  • 2
  • 28
  • 36