Microsoft MVP성태의 닷넷 이야기
.NET Framework: 294. Master web.config 파일을 수정하려면? [링크 복사], [링크+제목 복사],
조회: 24071
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13516정성태1/7/20249725닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20249672닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20249543개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20249669닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20249956개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20249672닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20249417닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/202410593오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/202410058오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/202411157닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/202310305닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/202312137닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/202311269닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/202310433Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/202310970닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/202310314개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/202310814디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/202312481닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/202310664오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/202310577Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/202310824Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/202310911Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/202311027닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/202310410개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20239405Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/202310136개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...