sourcetip

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

fileupload 2023. 6. 12. 21:50
반응형

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

런타임에 web.config 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>

예를 들어, 런타임에 "homepageesc" 키를 수정하고 싶습니다.구성 관리자 및 웹 구성 관리자 정적 클래스를 시도했지만 설정이 "읽기 전용"입니다.런타임에 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 SERVICE입니다(IIS 버전에 따라 다름).

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

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 world의 현재 상황을 바탕으로 답변을 올리고 싶었습니다.

저는 최근 회사에서 web.config 파일의 모든 appSettings & connectionStrings 설정을 한 곳에서 통합하고 관리하고자 하는 프로젝트를 주도했습니다.저는 프로젝트 성숙도와 안정성 때문에 우리의 구성 설정이 ZooKeper에 저장되는 접근 방식을 추구하고 싶었습니다.ZooKeeper가 구성 및 클러스터 관리 애플리케이션을 설계했다는 사실은 말할 것도 없습니다.

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

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

ASP.NET이 ZooKeper와 대화할 수 있도록 하는 기술적인 부분을 통과한 후, 저는 재빨리 다음 코드로 벽을 찾았습니다.

ConfigurationManager.AppSettings.Add(key_name, data_value)

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

약간의 조사를 하고 사람들이 이 문제를 해결하기 위해 다양한 미친 방법으로 일하는 것을 본 후, 저는 매우 낙담했습니다.이상적인 시나리오가 아닌 것처럼 보이는 것에 대해 포기하거나 안주하는 대신, 저는 무언가를 놓치고 있지 않은지 파고들기로 결심했습니다.

약간의 시행착오를 겪으면서, 저는 다음 코드가 제가 원하는 것을 정확히 할 수 있다는 것을 발견했습니다.

ConfigurationManager.AppSettings.Set(key_name, data_value)

이 코드 라인을 사용하여 이제 Application_Start의 ZooKeper에서 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(윈도우 7)에서 IIS 7.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();
        }
    }
}

언급URL : https://stackoverflow.com/questions/719928/how-do-you-modify-the-web-config-appsettings-at-runtime

반응형