반응형
중첩된 키(nested keys)란?
중첩된 키란 appsettings.json 같은 설정 파일에서 하위 계층 구조를 갖는 설정 값들을 의미한다. 즉, JSON의 객체 안에 또 다른 객체가 있는 경우를 말한다. 예시를 살펴보자. 다음과 같은 appsettings.json이 있다고 해보자.
{
"AppSettings": {
"Api": {
"BaseUrl": "https://api.example.com",
"ApiKey": "secret-key"
}
}
}
- 이 구조는 계층적으로 중첩(nested) 되어 있음
- AppSettings 최상위 키
- AppSettings:Api 중첩된 객체
- AppSettings:Api:BaseUrl 최종 키
JSON 구조 <=> 환경 변수 키
.NET은 구분자 :을 __(밑줄 2개)로 치환하는 규칙을 제공한다.
AppSettings:Api:BaseUrl <=> AppSettings__Api__BaseUrl
Logging:LogLevel:Default <=> Logging__LogLevel__Default
# Windows CMD
set AppSettings__Api__BaseUrl=https://env-api.example.com
환경 변수로 appsettings.json에 정의되어 있는 값을 덮어쓰기 하면 기존에 설정되는 값보다 환경변수로 설정된 값을 우선시한다.
C# 코드에서 환경변수 값 가져오기
해당 값은 IConfiguration 인터페이스 객체를 주입받은 configuration 객체를 통해서 접근이 가능하다.
해당 방식은 configuration 객체를 인덱서 방식으로 접근해서 설정값을 가져오는 예제이다.
string url = configuration["AppSettings:Api:BaseUrl"]; // 덮어쓰기 된 값 https://env-api.example.com
string key = configuration["AppSettings:Api:ApiKey"]; // 원래 값
추가적으로 해당 설정값을 애플리케이션 시작 시에 환경 변수를 설정해서 덮어쓰기 하는 게 가능하다.
이때 중첩된 키를 환경 변수로 덮어쓰기 하는 방법에 대해서 알아보자.
- appsettings.json
- appsettings.{Environment}.json
- UserSecrets
- 환경 변수
- 커맨드라인 인자
new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment}.json", optional: true)
.AddUserSecrets() // 개발 환경일 경우
.AddEnvironmentVariables()
.AddCommandLine(args);
해당 순서대로 값이 설정되기 때문에 설정값 추가 및 사용 시 주의를 기울여야 한다.
'프로그래밍 > C#' 카테고리의 다른 글
C# 2개의 list 하나로 합치기 (0) | 2025.03.30 |
---|---|
JSON 점 표기법(Dot Notation)에 대해서 (0) | 2025.03.06 |
EF Core에서 Find() vs Local.Where() 차이점 (0) | 2025.03.05 |
C# 컴퓨터가 문자를 표현하는 방법, 문자 인코딩 (0) | 2025.02.20 |
C# 폴더 안에 있는 모든 파일 찾기 (0) | 2025.01.23 |
댓글