Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

C# - appsettings.json 파일의 설정값이 적용 안 된다면?

이상하군요, 분명히 웹 애플리케이션의 배포 경로에는 appsettings.json 파일이 있고, 그 안에 설정값까지 넣어두었습니다.

$ cat appsettings.json
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },

    "AllowedHosts": "*",

    "ConnectionStrings": {
        "DBLocal": "...[생략]..."
    }
}

그런데 Microsoft.Extensions.Configuration.IConfiguration.GetConnectionString 메서드에서는 null을 반환합니다. 반면, 비주얼 스튜디오에서 디버깅을 해보면 ^^; 값이 잘 반환됩니다.

검색해 보니까,

Published .Net Core 2 application does not read appsettings.json file
; https://stackoverflow.com/questions/50578013/published-net-core-2-application-does-not-read-appsettings-json-file

Current Directory를 기준으로 찾기 때문이라고 합니다. 그러니까, 아래와 같은 식으로 실행하면 안 되는 것입니다.

// 아래와 같은 경우라면, "/appsettings.json" 경로의 파일을 찾게 되므로 의도한 대로 실행이 안 됨.

$ pwd
/

$ dotnet /app/core3web/Core3Web.dll

대신 이렇게 실행해야 합니다.

// 아래의 경우라면, "/app/core3web/appsettings.json" 경로의 파일을 찾게 되므로 의도한 대로 실행.

$ cd /app/core3web
$ dotnet Core3Web.dll

쉬운 내용이다 보니 너무 쉽게 간과할 수 있던 부분입니다. ^^ 따라서 만약 다른 경로에서 "dotnet /app/core3web/Core3Web.dll"과 같은 식으로 실행하는 것도 허용하고 싶다면 Current Directory를 변경해야 합니다. "Published .Net Core 2 application does not read appsettings.json file" 글의 답변에는 이에 대한 해결책으로 AppContext.BaseDirectory를 이용했다고 하는데 좋은 우회책인 것 같습니다. ^^

namespace Core3Web;

public class Program
{
    public static void Main(string[] args)
    {
        Environment.CurrentDirectory = AppContext.BaseDirectory;
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.ListenAnyIP(6001);
                });
            });
}




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







[최초 등록일: ]
[최종 수정일: 8/20/2025]

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

비밀번호

댓글 작성자
 




... 106  107  108  109  [110]  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11257정성태7/31/201720993.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201723266디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201725870디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201722225개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201723362Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201720184오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201720495디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201724336디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201721747오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201728348오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
11247정성태7/12/201722765오류 유형: 408. SqlConnection 객체 생성 시 무한 대기 문제파일 다운로드1
11246정성태7/11/201719867VS.NET IDE: 118. Visual Studio - 다중 폴더에 포함된 파일들에 대한 "Copy to Output Directory"를 한 번에 설정하는 방법
11245정성태7/10/201725690개발 환경 구성: 321. Visual Studio Emulator for Android 소개 [2]
11244정성태7/10/201726899오류 유형: 407. Visual Studio에서 ASP.NET Core 실행할 때 dotnet.exe 프로세스의 -532462766 오류 발생 [1]
11243정성태7/10/201723728.NET Framework: 666. dotnet.exe - 윈도우 운영체제에서의 .NET Core 버전 찾기 규칙
11242정성태7/8/201722450제니퍼 .NET: 27. 제니퍼 닷넷 적용 사례 (7) - 노후된 스토리지 장비로 인한 웹 서비스 Hang (멈춤) 현상
11241정성태7/8/201720881오류 유형: 406. Xamarin 빌드 에러 XA5209, APT0000
11240정성태7/7/201725587.NET Framework: 665. ClickOnce를 웹 브라우저를 이용하지 않고 쿼리 문자열을 전달하면서 실행하는 방법 [3]파일 다운로드1
11239정성태7/6/201725300.NET Framework: 664. Protocol Handler - 웹 브라우저에서 데스크톱 응용 프로그램을 실행하는 방법 [5]파일 다운로드1
11238정성태7/6/201722808오류 유형: 405. NT 서비스 시작 시 "Error 1067: The process terminated unexpectedly." 오류 발생 [2]
11237정성태7/5/201724674.NET Framework: 663. C# - PDB 파일 경로를 PE 파일로부터 얻는 방법파일 다운로드1
11236정성태7/4/201728436.NET Framework: 662. C# - VHD/VHDX 가상 디스크를 마운트하지 않고 파일을 복사하는 방법파일 다운로드1
11235정성태6/29/201723020Math: 20. Matlab/Octave로 Gram-Schmidt 정규 직교 집합 구하는 방법
11234정성태6/29/201721007오류 유형: 404. SharePoint 2013 설치 과정에서 "The username is invalid The account must be a valid domain account" 오류 발생
11233정성태6/28/201720924오류 유형: 403. SharePoint Server 2013을 Windows Server 2016에 설치할 때 .NET 4.5 설치 오류 발생
11232정성태6/28/201721755Windows: 144. Windows Server 2016에 Windows Identity Extensions을 설치하는 방법
... 106  107  108  109  [110]  111  112  113  114  115  116  117  118  119  120  ...