Adding values ​​to web configuration dynamically? How To + Best Way

I just came up with reading, writing and adding values ​​dynamically in web.Config in asp.net. Keep a lot of ideas in mind, but I just wana know what is the best way to add values ​​to the web configuration dynamically.

for example in my case i have to add

<identity userName="someDomain\User" password="password" impersonate="true" /> 

in

tag

in the web configuration from the code behind.

Waiting for Good Answers

+4
source share
4 answers

I got you and the code you want:

  public void saveIdentity(string username, string password, bool impersonate) { Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~"); IdentitySection identitySection = (IdentitySection)objConfig.GetSection("system.web/identity"); if (identitySection != null) { identitySection.UserName = username; identitySection.Password = password; identitySection.Impersonate = impersonate; } objConfig.Save(); } 
+5
source

I would recommend you not try to update web.config dynamically. This will restart your application and your user session will expire.

by making changes to the following, your application will always restart

 * web.config * machine.config * global.asax * Anything in the bin directory or it sub-directories 

See aspnet-application-restarts.html for more details.

+4
source

Why are you trying to set the identifier in the code? This is usually what you need to configure when the application is deployed and then left alone. If you can explain what you are trying to accomplish, we can offer a better way to do this.

Also, do you know that changing the web configuration will restart the application? All server-side caching will be reset, user sessions will end, etc. Just because a tool exists to modify web configuration from code does not mean that it is a good idea.

+1
source

This is in a desktop application, but we can use it in a web application

 if (Convert.ToInt32(txtPortNumber.Text.Trim()) <= 65535) { System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); System.Net.Configuration.MailSettingsSectionGroup mailSection = config.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup; mailSection.Smtp.From = txtFrom.Text.Trim(); mailSection.Smtp.Network.Host = txtFrom.Text.Trim(); mailSection.Smtp.Network.UserName = txtFrom.Text.Trim(); mailSection.Smtp.Network.Password = txtPassword.Text.Trim(); mailSection.Smtp.Network.EnableSsl = chkEnableSSL.Checked; mailSection.Smtp.Network.Port = Convert.ToInt32(txtPortNumber.Text.Trim()); config.Save(ConfigurationSaveMode.Modified); MessageBox.Show("Your mail setting has been saved successfully."); Application.Restart(); } else { MessageBox.Show("Port number is not valid, please enter port number between the 0 to 65535."); } 
+1
source

Source: https://habr.com/ru/post/1343910/


All Articles