动态添加Web配置中的值? 如何+最佳方式

我只想在asp.net中的web.Config中动态地阅读,编写和添加值。 记住了很多想法,但我知道什么是动态添加web配置中值的最佳方法。

例如,在我的情况下,我必须添加

 

从后面的代码标记web配置。

等待好的回应

我找到了你想要的代码是:

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

我建议你不要尝试动态更新web.config。 通过这样做,您的应用程序将重新启动,您的用户会话将过期。

通过执行以下更改,您的应用程序将始终重新启动

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

有关详细信息,请查看aspnet-application-restarts.html

你为什么要在代码中设置身份? 这通常应该在部署应用程序时预先设置,然后单独保留。 如果你能解释你想要实现的目标,我们可以提出一个更好的方法来做到这一点。

除此之外,您是否知道更改Web配置会导致应用重启? 您的所有服务器端缓存都将被转储,用户会话将被终止等等。仅仅因为存在从代码修改Web配置的工具并不意味着这样做是个好主意。

这是在桌面应用程序中,但我们可以在Web应用程序中使用它

 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."); }