configurationManager.Refreshsection을 사용하여 응용 프로그램을 다시 시작하지 않고 구성 새로로드합니다

StackOverflow https://stackoverflow.com/questions/179254

문제

웹 애플리케이션 에서이 작업을 수행 한 사람이 있습니까?

내가 무엇을하든 내 appSettings 섹션 (appSettings file = ".

응용 프로그램을 다시 시작 해야하는 경우에 따라 운명이 있습니까? 이 방법이 저를보다 성능있는 솔루션으로 이끌어주기를 바랐습니다.

업데이트:

'Reloading'을 통해 ConfigurationManager.Appsettings는 ASP.NET 응용 프로그램을 완전히 다시 시작하지 않고 일반적인 시작 대기 시간을 발생시켜야합니다.

도움이 되었습니까?

해결책

올바른 것을 통과하고 있는지 확인하십시오 사례에 민감합니다 새로 고침의 가치, 즉

ConfigurationManager.RefreshSection("appSettings");

다른 팁

AppSettings에 외부 구성 파일을 사용할 때는 결함 (아마도 버그) 인 것 같습니다. ConfigSource 속성을 사용하여 시도했으며 새로 고침은 단순히 작동하지 않습니다. 파일 속성을 사용할 때 동일하다고 가정합니다. appsetting을 웹 내부로 다시 움직이면 Config Refreshsection이 완벽하게 작동하지만 그렇지 않으면 운명이 두렵습니다.

몇 가지 이유 ConfigurationManager.RefreshSection("appSettings") 나를 위해 일하지 않았습니다. web.config를 구성 객체로 다시로드하는 것은 올바르게 작동하는 것 같습니다. 다음 코드는 web.config 파일이 실행 (BIN) 폴더 아래의 하나의 디렉토리라고 가정합니다.

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
Uri uriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
string appPath = uriAssemblyFolder.LocalPath;
configMap.ExeConfigFilename = appPath + @"\..\" + "Web.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); 

다음과 같이 사용됩니다.

string webConfigVariable = config.AppSettings.Settings["webConfigVariable"].Value;

대안으로 당신은 당신 자신의 쓸 수 있습니다 ConfigSection 그리고 설정 restartOnExternalChanges="false".

그런 다음 섹션을 읽을 때 ConfigurationManager.GetSection("yourSection") 설정이 있습니다 응용 프로그램 재시작없이 자동 반영.

또한 설정을 강력하게 입력하거나 NameValueCollection으로 구현할 수 있습니다.

.refreshsection ()는 appSettings가 외부 일 때 작동하지 않습니다.

그러나 다음을 사용하여 값을 변경할 수 있습니다.

ConfigurationManager.AppSettings.Set(key, value)

이것은 파일의 설정을 변경하지 않고 메모리의로드 된 값 만 변경합니다.

새로 고침을 사용하는 대신 다음을 수행했습니다.

string configFile="path to your config file";
XmlDocument xml = new XmlDocument();
xml.Load(configFile);

foreach (XmlNode node in xml.SelectNodes("/appSettings/add"))
{
    string key = node.Attributes["key"].Value;
    string value= node.Attributes["value"].Value;
    ConfigurationManager.AppSettings.Set(key, value);
}

이후의 모든 호출 appsettings.get에는 업데이트 된 값이 포함됩니다.

그런 다음 응용 프로그램을 다시 시작하지 않고도 AppSettings가 업데이트됩니다.

예. 당신은 IIS 재시작에 붙어 있습니다.

초기 시작이 제거되는 ASP.NET 4.0 및 IIS 7.5 기능이 있습니다.

웹 앱에서 이것이 가능한지 확실하지 않지만 데스크탑 앱에서 작동합니다. configurationManager 대신 configurationSettings를 사용해보십시오 (구식 클래스를 사용하기 위해 소리를 지른 다음 모든 데이터를 클래스로 읽습니다. 새로 고치려면 새 인스턴스를 만들고 모든 참조를 이전 인스턴스에 삭제하십시오. 이것이 작동하는 이유에 대한 나의 이론 (잘못 될 수 있음) : app.config 파일에 직접 액세스하지 않으면 실행중인 전체 시간에 파일 잠금이 응용 프로그램에 의해 삭제됩니다. 그런 다음 파일에 액세스하지 않으면 편집 할 수 있습니다.

응용 프로그램이 시작될 때 app.config 설정은 메모리로 캐시됩니다. 이러한 이유로, 나는 당신이 당신의 응용 프로그램을 다시 시작하지 않고 해당 설정을 변경할 수 없다고 생각합니다. 매우 간단한 대안은 별도의 간단한 XML 구성 파일을 만들고 직접로드/캐싱/재 장전을 처리하는 것입니다.

글을 쓰려면이 방법으로 전화하십시오.

dim config as system.configuration.configuration = system.web.configuration.webConfigurationManager.openWebConfiguration ( "~")

let

캐시의 값 대신 파일에 값을 읽고 확인하려면 다음과 같은 방식으로 읽으십시오.

Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~")
  Return config.AppSettings.Settings("TheKeyYouWantTheValue").Value

Full example:

Protected Shared Function AddOrUpdateAppSetting( _
       ByVal Config As System.Configuration.Configuration _
     , ByVal TheKey As String _
     , ByVal TheValue As String _
     ) As Boolean</p>

    Dim retval As Boolean = True

    Dim Itm As System.Configuration.KeyValueConfigurationElement = _
        Config.AppSettings.Settings.Item(TheKey)
    If Itm Is Nothing Then
        If Config.AppSettings.Settings.IsReadOnly Then
        retval = False
        Else
        Config.AppSettings.Settings.Add(TheKey, TheValue)
        End If


    Else
        ' config.AppSettings.Settings(thekey).Value = thevalue
        If Itm.IsReadOnly Then
            retval = False
        Else
            Itm.Value = TheValue
        End If


    End If
    If retval Then
     Try
        Config.Save(ConfigurationSaveMode.Modified)

     Catch ex As Exception
        retval = False
     End Try

    End If

    Return retval

End Function

자체 외부 파일에 AppSetting을 저장해 보셨습니까?

app.config/web.config에서 :

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

AppSettings.config :

<?xml version="1.0"?>
<appSettings>
  <add key="SomeKey" value="SomeValue" />
</appSettings>

AppSettings.config에 대한 변경 사항은 즉시 반영되어야합니다. 더 많은 정보:http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top