[asp.net] 런타임에 web.config appSettings를 어떻게 수정합니까?

런타임에 web.config appSettings 값을 수정하는 방법에 대해 혼란 스럽습니다. 예를 들어이 appSettings 섹션이 있습니다.

<appSettings>
  <add key="productspagedesc" value="TODO: Edit this default message" />
  <add key="servicespagedesc" value="TODO: Edit this default message" />
  <add key="contactspagedesc" value="TODO: Edit this default message" />
  <add key="aboutpagedesc" value="TODO: Edit this default message" />
  <add key="homepagedesc" value="TODO: Edit this default message" />
 </appSettings>

런타임에 “homepagedesc”키를 수정하고 싶다고 가정 해 보겠습니다. ConfigurationManager 및 WebConfigurationManager 정적 클래스를 시도했지만 설정이 “읽기 전용”입니다. 런타임에 appSettings 값을 어떻게 수정합니까?

업데이트 : 좋아, 그래서 여기 나는 5 년 후이다. 경험에 따르면 web.config 파일에 의도적으로 런타임에 편집 할 수있는 구성을 넣지 말고 사용자가 아래에 언급 한대로 별도의 XML 파일에 넣어야합니다. 앱을 다시 시작하기 위해 web.config 파일을 편집 할 필요가 없습니다. 그러면 화난 사용자가 전화를 겁니다.



답변

다음을 사용해야합니다 WebConfigurationManager.OpenWebConfiguration(). 예 :

Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()

machine.config에서 AllowLocation 을 설정해야 할 수도 있습니다 . 요소를 사용하여 개별 페이지를 구성 할 수 있는지 여부를 나타내는 부울 값입니다. “allowLocation”이 false이면 개별 요소에서 구성 할 수 없습니다.

마지막으로 IIS에서 애플리케이션을 실행하고 Visual Studio에서 테스트 샘플을 실행하면 차이가 있습니다. ASP.NET 프로세스 ID는 IIS 계정, ASPNET 또는 NETWORK SERVICES (IIS 버전에 따라 다름)입니다.

web.config가있는 폴더에 대한 ASPNET 또는 NETWORK SERVICES 수정 액세스 권한을 부여해야 할 수 있습니다.


답변

web.config를 변경하면 일반적으로 응용 프로그램이 다시 시작됩니다.

응용 프로그램이 자체 설정을 편집해야하는 경우 설정을 데이터베이스 화하거나 편집 가능한 설정으로 xml 파일을 만드는 것과 같은 다른 접근 방식을 고려해야합니다.


답변

응용 프로그램을 다시 시작하지 않으려면 다음 appSettings섹션으로 이동할 수 있습니다 .

<appSettings configSource="Config\appSettings.config"/>

별도의 파일로. 그리고 함께ConfigurationSaveMode.Minimal

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);

appSettings애플리케이션을 다시 시작하지 않고 일반 appSettings 섹션과 다른 형식의 파일을 사용할 필요없이 섹션을 다양한 설정에 대한 저장소로 계속 사용할 수 있습니다 .


답변

2012
다음은이 시나리오에 대한 더 나은 솔루션입니다 ( Visual Studio 2008로 테스트 됨 ).

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();

업데이트 2018 =>
2015 년 대비 테스트-Asp.net MVC5

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();

요소가 있는지 확인해야하는 경우 다음 코드를 사용하십시오.

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();


답변

이 질문이 오래되었다는 것을 알고 있지만 실제 경험과 결합 된 ASP.NET \ IIS 세계의 현재 상황을 기반으로 답변을 게시하고 싶었습니다.

저는 최근에 회사에서 web.config 파일의 모든 appSettings 및 connectionStrings 설정을 한 곳에서 통합하고 관리하려는 프로젝트를 주도했습니다. 프로젝트 성숙도와 안정성으로 인해 구성 설정이 ZooKeeper에 저장되는 접근 방식을 추구하고 싶었습니다. ZooKeeper가 구성 및 클러스터 관리 응용 프로그램이라는 사실은 말할 것도 없습니다.

프로젝트 목표는 매우 간단했습니다.

  1. ZooKeeper와 통신하도록 ASP.NET 가져 오기
  2. Global.asax, Application_Start-ZooKeeper에서 web.config 설정을 가져옵니다.

ASP.NET이 ZooKeeper와 통신하도록하는 기술적 인 부분을 통과하자 다음 코드를 빠르게 찾아 벽에 부딪 혔습니다.

ConfigurationManager.AppSettings.Add(key_name, data_value)

이 문장은 내가 appSettings 컬렉션에 새로운 설정을 추가하고 싶었 기 때문에 가장 논리적으로 의미가 있습니다. 그러나 원본 포스터 (및 기타 많은)에서 언급했듯이이 코드 호출은 컬렉션이 읽기 전용임을 나타내는 오류를 반환합니다.

약간의 조사를하고 사람들이이 문제를 해결하는 모든 다른 미친 방법을 본 후에 나는 매우 낙담했습니다. 이상적인 시나리오가 아닌 것처럼 보이는 것에 대해 포기하거나 정착하는 대신, 나는 무언가를 놓치고 있는지 알아보기로 결정했습니다.

약간의 시행 착오를 거쳐 다음 코드가 내가 원하는 것을 정확히 수행한다는 것을 알았습니다.

ConfigurationManager.AppSettings.Set(key_name, data_value)

이 코드 줄을 사용하여 이제 내 Application_Start의 ZooKeeper에서 85 개의 appSettings 키를 모두로드 할 수 있습니다.

IIS 재활용을 트리거하는 web.config의 변경 사항에 대한 일반적인 설명과 관련하여 다음과 같은 appPool 설정을 편집하여 배후 상황을 모니터링했습니다.

appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True

이러한 설정 조합을 사용하여이 프로세스로 인해 appPool이 재활용되는 경우 이벤트 로그 항목이 기록되어야하는데 기록되지 않았습니다.

이것은 중앙 집중식 저장 매체에서 애플리케이션 설정을로드하는 것이 가능하고 실제로 안전하다는 결론을 내립니다.

Windows 7에서 IIS7.5를 사용하고 있음을 언급해야합니다. 코드는 Win2012의 IIS8에 배포 될 것입니다. 이 답변에 관한 사항이 변경되면 그에 따라이 답변을 업데이트하겠습니다.


답변

요점을 직접 좋아하는 사람,

구성에서

    <appSettings>

    <add key="Conf_id" value="71" />

  </appSettings>

귀하의 코드 (c #)

///SET
    ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
      ///GET              
    string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();


답변

이 시도:

using System;
using System.Configuration;
using System.Web.Configuration;

namespace SampleApplication.WebConfig
{
    public partial class webConfigFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
            //Save the Modified settings of AppSettings.
            webConfigApp.Save();
        }
    }
}