Microsoft MVP성태의 닷넷 이야기
.NET Framework: 294. Master web.config 파일을 수정하려면? [링크 복사], [링크+제목 복사],
조회: 24041
글쓴 사람
정성태 (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)
13667정성태7/7/20246623닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247700Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247884Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247482닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247491닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247413Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247523오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247864개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248243개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247918닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248098Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247858닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247788오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247937닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249250닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248488닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248410개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247967오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248289오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249345개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247765오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248201개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248868닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248323오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248201스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...