Microsoft MVP성태의 닷넷 이야기
.NET Framework: 294. Master web.config 파일을 수정하려면? [링크 복사], [링크+제목 복사],
조회: 17516
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

Master web.config 파일을 수정하려면?

예를 드는 것이 빠를 것 같군요. ^^

ASP.NET Case Study: Lost session variables and appdomain recycles
 - How do you determine what caused an appdomain restart?
; https://www.tessferrandez.com/blog/2006/08/02/aspnet-case-study-lost-session-variables-and-appdomain-recycles.html

위의 글을 보면, 웹 애플리케이션이 Recycle 되는 원인을 이벤트 로그에 남기도록 하는 설정을 추가하는 방법이 설명되어 있습니다. 이를 위해, master web.config 파일, 즉 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 폴더에 있는 web.config 파일을 변경해 주어야하는데요. 대충 다음과 같은 설정이 추가되어야 합니다.

<healthMonitoring>
    <rules>
        ...[생략]...
        <add name="Application Lifetime Events Default" eventName="Application Lifetime Events"
            provider="EventLogProvider" profile="Default" minInstances="1"
            maxLimit="Infinite" minInterval="00:01:00" custom="" />
    </rules>
</healthMonitoring>

그런데, 이런 작업을 수작업으로 해주는 것이 여간 귀찮아야 말이죠. ^^ 코딩으로 자동화해주는 것이 어떨까요?

하지만, 애석하게도 '제가 아는 방법 내에서는' "Master web.config" 파일을 자연스럽게 업데이트 하는 방법은 없었습니다. (혹시 아시는 분은 공개 좀 부탁드립니다. ^^)

엄밀히 말하면, 내용을 업데이트해서 메모리에 들고 있는 것까지는 가능한데 그것을 저장하는 방법이 '멋있지 않습니다.'




하나씩 풀어볼까요? 우선, "master web.config" 파일을 로드해야 하는데요. 다행히 OpenWebConfiguration 메서드를 이용하면 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 경로를 지정해야만 하는 부담감을 덜 수 있습니다.

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);

이렇게 null 인자를 주면 알아서 "master web.config" 파일을 로드해 줍니다. 그 다음부터는 원하는 Config Section을 얻어내서 변경을 가해주면 되는데요. 위의 healthMonitoring 같은 경우에는 아래와 같이 코딩을 해줄 수 있습니다.

ConfigurationSection section = config.GetSection("system.web/healthMonitoring");
if (section == null)
{
    return;
}

HealthMonitoringSection healthSection = section as HealthMonitoringSection;
if (healthSection == null)
{
    return;
}

foreach (RuleSettings rule in healthSection.Rules)
{
    if (rule.Name == "Application Lifetime Events Default" 
        && rule.EventName == "Application Lifetime Events")
    {
        return;
    }
}

RuleSettings ruleSettings = new RuleSettings(
        "Application Lifetime Events Default", "Application Lifetime Events", 
        "EventLogProvider", "Default", 1, Int32.MaxValue, new TimeSpan(0, 1, 0));

healthSection.Rules.Add(ruleSettings);

여기까지 코드를 실행하면, 메모리에 있는 config 인스턴스에만 내용이 변경된 상태입니다. 자... 문제는 이렇게 변경된 내용을 다시 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 경로에 저장해야 한다는 것인데요. 아쉽게도 이 방법이 제공되고 있지 않습니다.

일단, Configuration.Save와 Configuration.SaveAs 메서드가 제공되고 있기는 하지만 각각 문제가 있습니다.

Configuration.Save의 경우에는 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 폴더에 저장을 시도하긴 하지만 파일명을 무작위로 변환해서 저장합니다. 즉, 기존 master web.config 파일을 덮어쓰지 않습니다.

Configuration.SaveAs 파일은 경로를 지정할 수 있기 때문에 master web.config 파일 경로를 넣어줄 수는 있지만, 실제로 실행해 보면 다음과 같은 예외가 발생합니다.

System.ArgumentException was unhandled
  Message=The file name 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config' is invalid because the same file name is already referenced by the configuration hierarchy you have opened.
  Source=System.Configuration
  StackTrace:
       at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)
       at System.Configuration.Configuration.SaveAsImpl(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)
       at System.Configuration.Configuration.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)
       at System.Configuration.Configuration.SaveAs(String filename)
       at ConsoleApplication1.Program.AddOrUpdateAppDomainRestartEventRule() in D:\...\ConsoleApplication1\Program.cs:line 56
       at ConsoleApplication1.Program.Main(String[] args) in D:\...\ConsoleApplication1\Program.cs:line 20
  InnerException: 

따라서, '수작업'으로 File Copy/Delete/Move와 같은 함수를 호출해서 처리해 주어야 합니다.

이 때문에, 제 경우에는 다음과 같이 기존 master web.config 파일을 web.[날짜].config 파일로 백업하고 새롭게 설정한 내용을 web.config 로 쓰는 방식으로 처리를 했습니다.

// 기존 파일을 backup 해놓고.
string dateTime = GetDateTimeAsString(DateTime.Now);
string backupFilePath = Path.ChangeExtension(config.FilePath, dateTime + ".config");
File.Copy(config.FilePath, backupFilePath);

string oldConfigPath = config.FilePath; // oldConfigPath == web.config
File.Delete(config.FilePath + ".candidate");
config.SaveAs(config.FilePath + ".candidate");
File.Delete(oldConfigPath);

File.Move(config.FilePath, oldConfigPath);

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.

문제는 여기서 끝이 아닙니다. .NET 2.0과 .NET 4.0 폴더가 다르고 x86/x64마다 있으므로 그에 대한 처리를 모두 해줄 수 있어야 합니다.

x86 .NET 2.0: C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
x86 .NET 4.0: C:\Windows\Microsoft.NET\Framework\v4.0.30319\CONFIG

x64 .NET 2.0: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
x64 .NET 4.0: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\CONFIG

각각의 개별 exe 파일을 만들던가... 아니면 web.config 파일 자체를 XML로 다루던가... 마지막으로 이전에 써두었던 다음과 같은 방법을 이용해 보는 것도 좋을 것입니다. ^^

x86/x64로 구분된 코드를 포함하는 경우, 다중으로 어셈블리를 만들어야 할까요?
; https://www.sysnet.pe.kr/2/0/1207

설치된 .NET 버전에 민감한 코드를 포함하는 경우, 다중으로 어셈블리를 만들어야 할까요?
; https://www.sysnet.pe.kr/2/0/1178




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/21/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13425정성태10/11/20233426닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233445스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233551닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233653닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20236168스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233372스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20234205닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233723닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233423오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233914닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233761디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233946닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237282닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233740Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235331닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20234100닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20234087Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233794닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233826VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20234236닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233749오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233590오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233681닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233919닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233790오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233630닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...